Xinqi Bao's Git

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