1 // vim:ts=4:sw=4:expandtab
3 #include <sys/socket.h>
4 #include <netinet/in.h>
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
20 const char *get_ip_addr(const char *interface, int family) {
21 static char part[512];
23 if (family == AF_INET)
24 len = sizeof(struct sockaddr_in);
25 else if (family == AF_INET6)
26 len = sizeof(struct sockaddr_in6);
28 memset(part, 0, sizeof(part));
30 struct ifaddrs *ifaddr, *addrp;
32 int interface_len = strlen(interface);
39 /* Skip until we are at the input family address of interface */
43 (strncmp(addrp->ifa_name, interface, interface_len) != 0 ||
44 addrp->ifa_addr == NULL ||
45 addrp->ifa_addr->sa_family != family));
47 addrp = addrp->ifa_next) {
48 /* Check if the interface is down */
49 if (strncmp(addrp->ifa_name, interface, interface_len) != 0)
52 if ((addrp->ifa_flags & IFF_RUNNING) == 0) {
60 return (found ? "no IP" : NULL);
64 if ((ret = getnameinfo(addrp->ifa_addr, len, part, sizeof(part), NULL, 0, NI_NUMERICHOST)) != 0) {
65 fprintf(stderr, "i3status: getnameinfo(): %s\n", gai_strerror(ret));