Xinqi Bao's Git

Fix ram_free for Linux
[slstatus.git] / components / ip.c
1 /* See LICENSE file for copyright and license details. */
2 #include <errno.h>
3 #include <ifaddrs.h>
4 #include <netdb.h>
5 #include <stdio.h>
6 #include <string.h>
7 #if defined(__OpenBSD__)
8 #include <sys/types.h>
9 #include <sys/socket.h>
10 #endif
11
12 #include "../util.h"
13
14 const char *
15 ipv4(const char *iface)
16 {
17 struct ifaddrs *ifaddr, *ifa;
18 int s;
19 char host[NI_MAXHOST];
20
21 if (getifaddrs(&ifaddr) < 0) {
22 warn("getifaddrs:");
23 return NULL;
24 }
25
26 for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
27 if (!ifa->ifa_addr) {
28 continue;
29 }
30 s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), host,
31 NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
32 if (!strcmp(ifa->ifa_name, iface) &&
33 (ifa->ifa_addr->sa_family == AF_INET)) {
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 ipv6(const char *iface)
49 {
50 struct ifaddrs *ifaddr, *ifa;
51 int s;
52 char host[NI_MAXHOST];
53
54 if (getifaddrs(&ifaddr) < 0) {
55 warn("getifaddrs:");
56 return NULL;
57 }
58
59 for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
60 if (!ifa->ifa_addr) {
61 continue;
62 }
63 s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in6), host,
64 NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
65 if (!strcmp(ifa->ifa_name, iface) &&
66 (ifa->ifa_addr->sa_family == AF_INET6)) {
67 if (s != 0) {
68 warn("getnameinfo: %s", gai_strerror(s));
69 return NULL;
70 }
71 return bprintf("%s", host);
72 }
73 }
74
75 freeifaddrs(ifaddr);
76
77 return NULL;
78 }