1 // vim:ts=4:sw=4:expandtab
3 #include <sys/socket.h>
4 #include <netinet/in.h>
16 * Return a copy of the .ifa_name field passed as argument where the optional
17 * IP label, if present, is removed.
20 * - strip_optional_label("eth0") => "eth0"
21 * - strip_optional_label("eth0:label") => "eth0"
23 * The memory for the returned string is obtained with malloc(3), and can be
28 static char *strip_optional_label(const char *ifa_name) {
29 char *copy = sstrdup(ifa_name);
31 char *ptr = strchr(copy, ':');
41 * Return the IP address for the given interface or "no IP" if the
42 * interface is up and running but hasn't got an IP address yet
45 const char *get_ip_addr(const char *interface, int family) {
46 static char part[512];
48 if (family == AF_INET)
49 len = sizeof(struct sockaddr_in);
50 else if (family == AF_INET6)
51 len = sizeof(struct sockaddr_in6);
53 memset(part, 0, sizeof(part));
55 struct ifaddrs *ifaddr, *addrp;
63 /* Skip until we are at the input family address of interface */
64 for (addrp = ifaddr; addrp != NULL; addrp = addrp->ifa_next) {
65 /* Strip the label if present in the .ifa_name field. */
66 char *stripped_ifa_name = strip_optional_label(addrp->ifa_name);
68 bool name_matches = strcmp(stripped_ifa_name, interface) != 0;
69 free(stripped_ifa_name);
71 /* The interface does not have the right name, skip it. */
75 if (addrp->ifa_addr != NULL && addrp->ifa_addr->sa_family == family) {
76 /* We found the right interface with the right address. */
80 /* Check if the interface is down. If it is, no need to look any
82 if ((addrp->ifa_flags & IFF_RUNNING) == 0) {
92 return (found ? "no IP" : NULL);
96 if ((ret = getnameinfo(addrp->ifa_addr, len, part, sizeof(part), NULL, 0, NI_NUMERICHOST)) != 0) {
97 fprintf(stderr, "i3status: getnameinfo(): %s\n", gai_strerror(ret));