]> git.sur5r.net Git - i3/i3status/blob - src/print_ip_addr.c
clang-format-3.5 -i **/*.[ch], update modeline
[i3/i3status] / src / print_ip_addr.c
1 // vim:ts=4:sw=4:expandtab
2 #include <sys/types.h>
3 #include <sys/socket.h>
4 #include <netinet/in.h>
5
6 #include <stdlib.h>
7 #include <stdio.h>
8 #include <string.h>
9 #include <netdb.h>
10 #include <ifaddrs.h>
11 #include <net/if.h>
12
13 #include "i3status.h"
14
15 /*
16  * Return the IP address for the given interface or "no IP" if the
17  * interface is up and running but hasn't got an IP address yet
18  *
19  */
20 const char *get_ip_addr(const char *interface) {
21     static char part[512];
22     socklen_t len = sizeof(struct sockaddr_in);
23     memset(part, 0, sizeof(part));
24
25     struct ifaddrs *ifaddr, *addrp;
26     bool found = false;
27
28     getifaddrs(&ifaddr);
29
30     if (ifaddr == NULL)
31         return NULL;
32
33     /* Skip until we are at the AF_INET address of interface */
34     for (addrp = ifaddr;
35
36          (addrp != NULL &&
37           (strcmp(addrp->ifa_name, interface) != 0 ||
38            addrp->ifa_addr == NULL ||
39            addrp->ifa_addr->sa_family != AF_INET));
40
41          addrp = addrp->ifa_next) {
42         /* Check if the interface is down */
43         if (strcmp(addrp->ifa_name, interface) != 0)
44             continue;
45         found = true;
46         if ((addrp->ifa_flags & IFF_RUNNING) == 0) {
47             freeifaddrs(ifaddr);
48             return NULL;
49         }
50     }
51
52     if (addrp == NULL) {
53         freeifaddrs(ifaddr);
54         return (found ? "no IP" : NULL);
55     }
56
57     int ret;
58     if ((ret = getnameinfo(addrp->ifa_addr, len, part, sizeof(part), NULL, 0, NI_NUMERICHOST)) != 0) {
59         fprintf(stderr, "i3status: getnameinfo(): %s\n", gai_strerror(ret));
60         freeifaddrs(ifaddr);
61         return "no IP";
62     }
63
64     freeifaddrs(ifaddr);
65     return part;
66 }