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\n", cmd);
18 	exit(1);
19 }
20 
21 int
22 main(int argc, char *argv[])
23 {
24 	struct sockaddr_in in, in2;
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 	while ((opt = getopt(argc, argv, "4:p:")) != -1) {
32 		switch (opt) {
33 		case '4':
34 			if (inet_pton(AF_INET, optarg, &in.sin_addr) <= 0)
35 				usage(argv[0]);
36 			break;
37 
38 		case 'p':
39 			in.sin_port = strtol(optarg, NULL, 10);
40 			in.sin_port = htons(in.sin_port);
41 			break;
42 
43 		default:
44 			usage(argv[0]);
45 		}
46 	}
47 
48 	if (in.sin_addr.s_addr == INADDR_ANY || in.sin_port == 0)
49 		usage(argv[0]);
50 
51 	s = socket(AF_INET, SOCK_DGRAM, 0);
52 	if (s < 0)
53 		err(2, "socket failed");
54 
55 	if (connect(s, (const struct sockaddr *)&in, sizeof(in)) < 0)
56 		err(2, "connect failed");
57 
58 	memset(&in2, 0, sizeof(in2));
59 	in2.sin_family = AF_UNSPEC;
60 	connect(s, (const struct sockaddr *)&in2, sizeof(in2));
61 
62 	n = sendto(s, buf, sizeof(buf), 0,
63 	    (const struct sockaddr *)&in, sizeof(in));
64 	if (n < 0)
65 		err(2, "sendto failed");
66 	else if (n != (int)sizeof(buf))
67 		errx(2, "sendto truncated data %d", n);
68 
69 	n = read(s, buf, sizeof(buf));
70 	if (n < 0)
71 		err(2, "read failed");
72 	printf("read %d, done\n", n);
73 
74 	exit(0);
75 }
76