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