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_PROTOCOL = 89; 17 18 19 int 20 main(int argc, char *argv[]) 21 { 22 int socketFamily = AF_INET; 23 24 if (argc > 1) { 25 if (!strcmp(argv[1], "-4")) 26 socketFamily = AF_INET; 27 else if (!strcmp(argv[1], "-6")) 28 socketFamily = AF_INET6; 29 } 30 31 int fd = socket(socketFamily, SOCK_RAW, TEST_PROTOCOL); 32 if (fd < 0) { 33 perror("socket"); 34 return -1; 35 } 36 37 sockaddr_storage saddr; 38 memset(&saddr, 0, sizeof(saddr)); 39 if (socketFamily == AF_INET) { 40 sockaddr_in *sa = (sockaddr_in *) &saddr; 41 sa->sin_family = AF_INET; 42 sa->sin_addr.s_addr = htonl(INADDR_LOOPBACK); 43 } else { 44 sockaddr_in6 *sa = (sockaddr_in6 *) &saddr; 45 sa->sin6_family = AF_INET6; 46 sa->sin6_addr.s6_addr[15] = 0x01; // loopback 47 } 48 49 const char *buffer = "hello world"; 50 unsigned length = strlen(buffer); 51 int status = sendto(fd, buffer, length, 0, (sockaddr *) &saddr, 52 socketFamily == AF_INET ? sizeof(sockaddr_in) : sizeof(sockaddr_in6)); 53 if (status < length) { 54 if (status < 0) 55 perror("sendto"); 56 else if (status == 0) 57 printf("no data sent!\n"); 58 else 59 printf("not all data sent!\n"); 60 } else 61 printf("send(): success\n"); 62 63 close(fd); 64 return 0; 65 } 66