test: Add bunch of tests for udp protocol
[dragonfly.git] / test / udp / bindsend / udp_bindsend.c
1 #include <sys/types.h>
2 #include <sys/socket.h>
3
4 #include <arpa/inet.h>
5 #include <netinet/in.h>
6
7 #include <err.h>
8 #include <stdio.h>
9 #include <stdint.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <unistd.h>
13
14 static void
15 usage(const char *cmd)
16 {
17         fprintf(stderr, "%s -4 ip4 -p port [-b ip4] -P bind_port\n", cmd);
18         exit(1);
19 }
20
21 int
22 main(int argc, char *argv[])
23 {
24         struct sockaddr_in in, local_in;
25         int s, opt, n;
26         uint8_t buf[18];
27
28         memset(&in, 0, sizeof(in));
29         in.sin_family = AF_INET;
30
31         memset(&local_in, 0, sizeof(local_in));
32         local_in.sin_family = AF_INET;
33
34         while ((opt = getopt(argc, argv, "4:P:b:p:")) != -1) {
35                 switch (opt) {
36                 case '4':
37                         if (inet_pton(AF_INET, optarg, &in.sin_addr) <= 0)
38                                 usage(argv[0]);
39                         break;
40
41                 case 'P':
42                         local_in.sin_port = strtol(optarg, NULL, 10);
43                         local_in.sin_port = htons(local_in.sin_port);
44                         break;
45
46                 case 'b':
47                         if (inet_pton(AF_INET, optarg, &local_in.sin_addr) <= 0)
48                                 usage(argv[0]);
49                         break;
50
51                 case 'p':
52                         in.sin_port = strtol(optarg, NULL, 10);
53                         in.sin_port = htons(in.sin_port);
54                         break;
55
56                 default:
57                         usage(argv[0]);
58                 }
59         }
60
61         if (in.sin_addr.s_addr == INADDR_ANY || in.sin_port == 0 ||
62             local_in.sin_port == 0)
63                 usage(argv[0]);
64
65         s = socket(AF_INET, SOCK_DGRAM, 0);
66         if (s < 0)
67                 err(2, "socket failed");
68
69         if (bind(s, (const struct sockaddr *)&local_in, sizeof(local_in)) < 0)
70                 err(2, "bind failed");
71
72         n = sendto(s, buf, sizeof(buf), 0,
73             (const struct sockaddr *)&in, sizeof(in));
74         if (n < 0)
75                 err(2, "sendto failed");
76         else if (n != (int)sizeof(buf))
77                 errx(2, "sent truncated data %d", n);
78
79         n = read(s, buf, sizeof(buf));
80         if (n < 0)
81                 err(2, "read failed");
82         printf("read %d, done\n", n);
83
84         exit(0);
85 }