xref: /haiku/src/tests/system/network/udp_connect.cpp (revision 495060760727dd782c9f8a90db71e5d727f19748)
1 /*
2  * Copyright 2010, Axel Dörfler, axeld@pinc-software.de.
3  * This file may be used under the terms of the MIT License.
4  */
5 
6 
7 #include <arpa/inet.h>
8 #include <netinet/in.h>
9 #include <sys/socket.h>
10 #include <stdio.h>
11 #include <string.h>
12 #include <unistd.h>
13 
14 
15 static bool sReceiveMode = false;
16 
17 
18 int
19 main(int argc, char** argv)
20 {
21 	const char* peerAddress = "192.168.0.1";
22 	if (argc > 1)
23 		peerAddress = argv[1];
24 
25 	if (argc > 2 && !strcmp(argv[2], "recv"))
26 		sReceiveMode = true;
27 
28 	int fd = socket(AF_INET, SOCK_DGRAM, 0);
29 	if (fd < 0)
30 		return 1;
31 
32 #if 1
33 	sockaddr_in addr;
34 	addr.sin_family = AF_INET;
35 	addr.sin_addr.s_addr = INADDR_ANY;
36 	addr.sin_port = htons(sReceiveMode ? 8888 : 0);
37 	if (bind(fd, (sockaddr*)&addr, sizeof(addr)) != 0)
38 		perror("bind");
39 
40 	sockaddr ours;
41 	socklen_t ourLength = sizeof(sockaddr);
42 	if (getsockname(fd, &ours, &ourLength) != 0)
43 		perror("getsockname");
44 	else {
45 		printf("After bind: local address %s (%u)\n",
46 			inet_ntoa(((sockaddr_in&)ours).sin_addr),
47 			ntohs(((sockaddr_in&)ours).sin_port));
48 	}
49 #endif
50 
51 	if (!sReceiveMode) {
52 		sockaddr_in peer;
53 		peer.sin_family = AF_INET;
54 		peer.sin_addr.s_addr = inet_addr(peerAddress);
55 		peer.sin_port = htons(sReceiveMode ? 0 : 8888);
56 		if (connect(fd, (sockaddr*)&peer, sizeof(peer)) != 0)
57 			perror("connect");
58 
59 		ourLength = sizeof(sockaddr);
60 		if (getsockname(fd, &ours, &ourLength) != 0)
61 			perror("getsockname");
62 		else {
63 			printf("After connect: local address %s (%u)\n",
64 				inet_ntoa(((sockaddr_in&)ours).sin_addr),
65 				ntohs(((sockaddr_in&)ours).sin_port));
66 		}
67 	}
68 
69 	char buffer[256];
70 	if (sReceiveMode) {
71 		ssize_t bytesReceived = recv(fd, buffer, sizeof(buffer), 0);
72 		if (bytesReceived > 0) {
73 			buffer[bytesReceived] = 0;
74 			printf("received: %s\n", buffer);
75 		} else
76 			perror("recv");
77 	} else {
78 		if (argc > 2)
79 			send(fd, argv[2], strlen(argv[2]), 0);
80 		else {
81 			fgets(buffer, sizeof(buffer), stdin);
82 			send(fd, buffer, strlen(buffer), 0);
83 		}
84 	}
85 
86 	close(fd);
87 	return 0;
88 }
89 
90 
91