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