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 */
40 for (addrp = ifaddr; addrp != NULL; addrp = addrp->ifa_next) {
41 if (strncmp(addrp->ifa_name, interface, interface_len) != 0) {
42 /* The interface does not have the right name, skip it. */
46 if (addrp->ifa_addr != NULL && addrp->ifa_addr->sa_family == family) {
47 /* We found the right interface with the right address. */
51 /* Check if the interface is down. If it is, no need to look any
53 if ((addrp->ifa_flags & IFF_RUNNING) == 0) {
63 return (found ? "no IP" : NULL);
67 if ((ret = getnameinfo(addrp->ifa_addr, len, part, sizeof(part), NULL, 0, NI_NUMERICHOST)) != 0) {
68 fprintf(stderr, "i3status: getnameinfo(): %s\n", gai_strerror(ret));