xref: /haiku/src/tests/system/network/ipv6/tcp_udp_client.cpp (revision 13581b3d2a71545960b98fefebc5225b5bf29072)
1 /*
2  * Copyright 2010, Atis Elsts, the.kfx@gmail.com
3  * Distributed under the terms of the MIT license.
4  */
5 
6 
7 #include <unistd.h>
8 #include <memory.h>
9 #include <netinet/in.h>
10 #include <arpa/inet.h>
11 #include <errno.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 
15 
16 const unsigned short TEST_PORT = 40000;
17 
18 
19 void
20 usage()
21 {
22 	printf("client [tcp|udp] [4|6] [4|6]\n");
23 	exit(1);
24 }
25 
26 
27 int
28 main(int argc, char *argv[])
29 {
30 	int socketType = SOCK_DGRAM;
31 	int socketFamily1 = AF_INET;
32 	int socketFamily2 = AF_INET;
33 
34 	if (argc > 1) {
35 		if (!strcmp(argv[1], "tcp"))
36 			socketType = SOCK_STREAM;
37 		else if (!strcmp(argv[1], "udp"))
38 			socketType = SOCK_DGRAM;
39 		else
40 			usage();
41 	}
42 	if (argc > 2) {
43 		switch (atoi(argv[2])) {
44 		case 4:
45 			socketFamily1 = AF_INET;
46 			break;
47 		case 6:
48 			socketFamily1 = AF_INET6;
49 			break;
50 		default:
51 			usage();
52 		}
53 	}
54 	if (argc > 3) {
55 		switch (atoi(argv[3])) {
56 		case 4:
57 			socketFamily2 = AF_INET;
58 			break;
59 		case 6:
60 			socketFamily2 = AF_INET6;
61 			break;
62 		default:
63 			usage();
64 		}
65 	}
66 
67 	int fd = socket(socketFamily1, socketType, 0);
68 	if (fd < 0) {
69 		perror("socket");
70 		return -1;
71 	}
72 
73 	sockaddr_storage saddr;
74 	memset(&saddr, 0, sizeof(saddr));
75 	saddr.ss_family = socketFamily2;
76 	((sockaddr_in *) &saddr)->sin_port = htons(TEST_PORT);
77 	if (connect(fd, (sockaddr *) &saddr, socketFamily2 == AF_INET ?
78 			sizeof(sockaddr_in) : sizeof(sockaddr_in6)) < 0) {
79 		perror("connect");
80 		close(fd);
81 		return -1;
82 	}
83 
84 	const char *buffer = "hello world";
85 	unsigned length = strlen(buffer);
86 	int status = send(fd, buffer, length, 0);
87 	if (status < length) {
88 		if (status < 0)
89 			perror("send");
90 		else if (status == 0)
91 			printf("no data sent!\n");
92 		else
93 			printf("not all data sent!\n");
94 	} else
95 		printf("send(): success\n");
96 	close(fd);
97 	return 0;
98 }
99