ccanlint: print coverage amount when -vv
[ccan] / ccan / net / tools / test-net.c
1 #include <ccan/net/net.h>
2 #include <sys/types.h>
3 #include <sys/socket.h>
4 #include <netdb.h>
5 #include <stdio.h>
6 #include <err.h>
7
8 static unsigned int count_addrs(const struct addrinfo *addr, int family)
9 {
10         unsigned int num = 0;
11
12         while (addr) {
13                 if (family == AF_UNSPEC || family == addr->ai_family)
14                         num++;
15                 addr = addr->ai_next;
16         }
17         return num;
18 }
19
20 int main(int argc, char *argv[])
21 {
22         struct addrinfo *addr;
23         const char *dest, *port;
24         int fd;
25         struct sockaddr saddr;
26         socklen_t slen = sizeof(saddr);
27
28         if (argc == 2) {
29                 dest = argv[1];
30                 port = "http";
31         } else if (argc == 3) {
32                 dest = argv[1];
33                 port = argv[2];
34         } else
35                 errx(1, "Usage: test-net <target> [<port>]");
36
37         addr = net_client_lookup(dest, port, AF_UNSPEC, SOCK_STREAM);
38         if (!addr)
39                 err(1, "Failed to look up %s", dest);
40
41         printf("Received %u IPv4 addresses, %u IPv6 addresses\n",
42                count_addrs(addr, AF_INET), count_addrs(addr, AF_INET6));
43
44         fd = net_connect(addr);
45         if (fd < 0)
46                 err(1, "Failed to connect to %s", dest);
47
48         if (getsockname(fd, &saddr, &slen) == 0)
49                 printf("Connected via %s\n",
50                        saddr.sa_family == AF_INET6 ? "IPv6"
51                        : saddr.sa_family == AF_INET ? "IPv4"
52                        : "UNKNOWN??");
53         else
54                 err(1, "Failed to get socket type for connection");
55         return 0;
56 }