slstatus

status monitor
git clone git://git.suckless.org/slstatus
Log | Files | Refs | README | LICENSE

ip.c (1207B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <ifaddrs.h>
      3 #include <netdb.h>
      4 #include <stdio.h>
      5 #include <string.h>
      6 #if defined(__OpenBSD__)
      7 	#include <sys/socket.h>
      8 	#include <sys/types.h>
      9 #elif defined(__FreeBSD__)
     10 	#include <netinet/in.h>
     11 	#include <sys/socket.h>
     12 #endif
     13 
     14 #include "../slstatus.h"
     15 #include "../util.h"
     16 
     17 static const char *
     18 ip(const char *interface, unsigned short sa_family)
     19 {
     20 	struct ifaddrs *ifaddr, *ifa;
     21 	int s;
     22 	char host[NI_MAXHOST];
     23 
     24 	if (getifaddrs(&ifaddr) < 0) {
     25 		warn("getifaddrs:");
     26 		return NULL;
     27 	}
     28 
     29 	for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
     30 		if (!ifa->ifa_addr)
     31 			continue;
     32 
     33 		s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in6),
     34 		                host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
     35 		if (!strcmp(ifa->ifa_name, interface) &&
     36 		    (ifa->ifa_addr->sa_family == sa_family)) {
     37 			freeifaddrs(ifaddr);
     38 			if (s != 0) {
     39 				warn("getnameinfo: %s", gai_strerror(s));
     40 				return NULL;
     41 			}
     42 			return bprintf("%s", host);
     43 		}
     44 	}
     45 
     46 	freeifaddrs(ifaddr);
     47 
     48 	return NULL;
     49 }
     50 
     51 const char *
     52 ipv4(const char *interface)
     53 {
     54 	return ip(interface, AF_INET);
     55 }
     56 
     57 const char *
     58 ipv6(const char *interface)
     59 {
     60 	return ip(interface, AF_INET6);
     61 }