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 int
main(int argc,char * argv[])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_DGRAM, 0);
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_port = htons(TEST_PORT);
43 sa->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
44 } else {
45 sockaddr_in6 *sa = (sockaddr_in6 *) &saddr;
46 sa->sin6_family = AF_INET6;
47 sa->sin6_port = htons(TEST_PORT);
48 sa->sin6_addr.s6_addr[15] = 0x01; // loopback
49
50 // 2001::1
51 // sa->sin6_addr.s6_addr[0] = 0x20;
52 // sa->sin6_addr.s6_addr[1] = 0x01;
53 // sa->sin6_addr.s6_addr[15] = 0x01;
54 }
55
56 const char *buffer = "hello world";
57 unsigned length = strlen(buffer);
58 int status = sendto(fd, buffer, length, 0, (sockaddr *) &saddr,
59 socketFamily == AF_INET ? sizeof(sockaddr_in) : sizeof(sockaddr_in6));
60 if (status < length) {
61 if (status < 0)
62 perror("sendto");
63 else if (status == 0)
64 printf("no data sent!\n");
65 else
66 printf("not all data sent!\n");
67 } else
68 printf("send(): success\n");
69
70 close(fd);
71 return 0;
72 }
73