]> git.sur5r.net Git - i3/i3status/blob - src/print_ip_addr.c
e719d2f6b228c96a4333abfe185c28b2b3cdd7fb
[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
26         getifaddrs(&ifaddr);
27
28         if (ifaddr == NULL)
29                 return NULL;
30
31         addrp = ifaddr;
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                     (addrp->ifa_flags & IFF_RUNNING) == 0) {
45                         freeifaddrs(ifaddr);
46                         return NULL;
47                 }
48         }
49
50         if (addrp == NULL) {
51                 freeifaddrs(ifaddr);
52                 return "no IP";
53         }
54
55         int ret;
56         if ((ret = getnameinfo(addrp->ifa_addr, len, part, sizeof(part), NULL, 0, NI_NUMERICHOST)) != 0) {
57                 fprintf(stderr, "getnameinfo(): %s\n", gai_strerror(ret));
58                 freeifaddrs(ifaddr);
59                 return "no IP";
60         }
61
62         freeifaddrs(ifaddr);
63         return part;
64 }
65