]> git.sur5r.net Git - i3/i3status/blob - src/get_ipv6_addr.c
2fd978be91f721b1cf322315f91d36c9bfb12004
[i3/i3status] / src / get_ipv6_addr.c
1 // vim:ts=8:expandtab
2 #include <stdio.h>
3 #include <unistd.h>
4 #include <stdlib.h>
5 #include <sys/types.h>
6 #include <sys/socket.h>
7 #include <netdb.h>
8 #include <string.h>
9 #include <arpa/inet.h>
10
11 /*
12  * Returns the IPv6 address with which you have connectivity at the moment.
13  *
14  */
15 const char *get_ipv6_addr() {
16         static char buf[INET6_ADDRSTRLEN+1];
17         struct addrinfo hints;
18         struct addrinfo *result, *resp;
19         int fd;
20
21         memset(&hints, 0, sizeof(struct addrinfo));
22         hints.ai_family = AF_INET6;
23
24         /* We resolve the K root server to get a public IPv6 address. You can
25          * replace this with any other host which has an AAAA record, but the
26          * K root server is a pretty safe bet. */
27         if (getaddrinfo("k.root-servers.net", "domain", &hints, &result) != 0) {
28                 perror("getaddrinfo()");
29                 return "no IP";
30         }
31
32         for (resp = result; resp != NULL; resp = resp->ai_next) {
33                 if ((fd = socket(resp->ai_family, SOCK_DGRAM, 0)) == -1) {
34                         perror("socket()");
35                         continue;
36                 }
37
38                 /* Since the socket was created with SOCK_DGRAM, this is
39                  * actually not establishing a connection or generating
40                  * any other network traffic. Instead, as a side-effect,
41                  * it saves the local address with which packets would
42                  * be sent to the destination. */
43                 if (connect(fd, resp->ai_addr, resp->ai_addrlen) == -1) {
44                         perror("connect()");
45                         (void)close(fd);
46                         continue;
47                 }
48
49                 struct sockaddr_storage local;
50                 socklen_t local_len = sizeof(struct sockaddr_storage);
51                 if (getsockname(fd, (struct sockaddr*)&local, &local_len) == -1) {
52                         perror("getsockname()");
53                         (void)close(fd);
54                         return "no IP";
55                 }
56
57                 (void)close(fd);
58
59                 memset(buf, 0, INET6_ADDRSTRLEN + 1);
60                 int ret;
61                 if ((ret = getnameinfo((struct sockaddr*)&local, local_len,
62                                        buf, sizeof(buf), NULL, 0,
63                                        NI_NUMERICHOST)) != 0) {
64                         fprintf(stderr, "getnameinfo(): %s\n", gai_strerror(ret));
65                         return "no IP";
66                 }
67
68                 free(result);
69                 return buf;
70         }
71
72         free(result);
73         return "no IP";
74 }