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