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