7 #include <sys/socket.h>
10 #include <arpa/inet.h>
12 static bool print_sockname(struct addrinfo *addr) {
13 static char buf[INET6_ADDRSTRLEN+1];
14 struct sockaddr_storage local;
18 if ((fd = socket(addr->ai_family, SOCK_DGRAM, 0)) == -1) {
23 /* Since the socket was created with SOCK_DGRAM, this is
24 * actually not establishing a connection or generating
25 * any other network traffic. Instead, as a side-effect,
26 * it saves the local address with which packets would
27 * be sent to the destination. */
28 if (connect(fd, addr->ai_addr, addr->ai_addrlen) == -1) {
29 /* We don’t display the error here because most
30 * likely, there just is no IPv6 connectivity.
31 * Thus, don’t spam the user’s console but just
32 * try the next address. */
38 socklen_t local_len = sizeof(struct sockaddr_storage);
39 if (getsockname(fd, (struct sockaddr*)&local, &local_len) == -1) {
40 perror("getsockname()");
46 memset(buf, 0, INET6_ADDRSTRLEN + 1);
47 if ((ret = getnameinfo((struct sockaddr*)&local, local_len,
48 buf, sizeof(buf), NULL, 0,
49 NI_NUMERICHOST)) != 0) {
50 fprintf(stderr, "getnameinfo(): %s\n", gai_strerror(ret));
62 * Returns the IPv6 address with which you have connectivity at the moment.
65 static void print_ipv6_addr() {
66 struct addrinfo hints;
67 struct addrinfo *result, *resp;
68 static struct addrinfo *cached = NULL;
70 /* To save dns lookups (if they are not cached locally) and creating
71 * sockets, we save the fd and keep it open. */
73 if (print_sockname(cached))
76 memset(&hints, 0, sizeof(struct addrinfo));
77 hints.ai_family = AF_INET6;
79 /* We resolve the K root server to get a public IPv6 address. You can
80 * replace this with any other host which has an AAAA record, but the
81 * K root server is a pretty safe bet. */
82 if (getaddrinfo("k.root-servers.net", "domain", &hints, &result) != 0) {
83 /* We don’t display the error here because most
84 * likely, there just is no connectivity.
85 * Thus, don’t spam the user’s console. */
90 for (resp = result; resp != NULL; resp = resp->ai_next) {
91 if (!print_sockname(resp))
94 if ((cached = malloc(sizeof(struct addrinfo))) == NULL)
96 memcpy(cached, resp, sizeof(struct addrinfo));
97 if ((cached->ai_addr = malloc(resp->ai_addrlen)) == NULL) {
101 memcpy(cached->ai_addr, resp->ai_addr, resp->ai_addrlen);
102 freeaddrinfo(result);
106 freeaddrinfo(result);
110 void print_ipv6_info(const char *format) {
113 for (walk = format; *walk != '\0'; walk++) {
119 if (strncmp(walk+1, "ip", strlen("ip")) == 0) {
121 walk += strlen("ip");