]> git.sur5r.net Git - i3/i3status/blob - src/get_ip_addr.c
Obtain IP address in a portable way, patch by Baptiste Daroussin
[i3/i3status] / src / get_ip_addr.c
1 // vim:ts=8:expandtab
2 #include <net/if.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
11 #include "i3status.h"
12
13 /*
14  * Return the IP address for the given interface or "no IP" if the
15  * interface is up and running but hasn't got an IP address yet
16  *
17  */
18 const char *get_ip_addr(const char *interface) {
19         static char part[512];
20         socklen_t len = sizeof(struct sockaddr_in);
21         memset(part, 0, sizeof(part));
22
23         struct ifaddrs *ifaddr, *addrp;
24
25         getifaddrs(&ifaddr);
26
27         if (ifaddr == NULL) {
28                 (void)snprintf(part, sizeof(part), "E: down");
29                 return part;
30         }
31
32         addrp = ifaddr;
33
34         /* Skip until we are at the AF_INET address of eth_interface */
35         for (addrp = ifaddr;
36
37              (addrp != NULL &&
38               (strcmp(addrp->ifa_name, eth_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, eth_interface) == 0 &&
45                     (addrp->ifa_flags & IFF_RUNNING) == 0)
46                         return NULL;
47         }
48
49         if (addrp == NULL)
50                 return "no IP";
51
52         int ret;
53         if ((ret = getnameinfo(addrp->ifa_addr, len, part, sizeof(part), NULL, 0, NI_NUMERICHOST)) != 0) {
54                 fprintf(stderr, "getnameinfo(): %s\n", gai_strerror(ret));
55                 return "no IP";
56         }
57
58         return part;
59 }
60