Xinqi Bao's Git

b1f8a0509c329161af21f16f931759ed31a9f926
[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) == -1) {
22 fprintf(stderr, "getifaddrs: %s\n", strerror(errno));
23 return NULL;
24 }
25
26 for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
27 if (ifa->ifa_addr == NULL) {
28 continue;
29 }
30 s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
31 if ((strcmp(ifa->ifa_name, iface) == 0) && (ifa->ifa_addr->sa_family == AF_INET)) {
32 if (s != 0) {
33 fprintf(stderr, "getnameinfo: %s\n", gai_strerror(s));
34 return NULL;
35 }
36 return bprintf("%s", host);
37 }
38 }
39
40 freeifaddrs(ifaddr);
41
42 return NULL;
43 }
44
45 const char *
46 ipv6(const char *iface)
47 {
48 struct ifaddrs *ifaddr, *ifa;
49 int s;
50 char host[NI_MAXHOST];
51
52 if (getifaddrs(&ifaddr) == -1) {
53 fprintf(stderr, "getifaddrs: %s\n", strerror(errno));
54 return NULL;
55 }
56
57 for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
58 if (ifa->ifa_addr == NULL) {
59 continue;
60 }
61 s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in6), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
62 if ((strcmp(ifa->ifa_name, iface) == 0) && (ifa->ifa_addr->sa_family == AF_INET6)) {
63 if (s != 0) {
64 fprintf(stderr, "getnameinfo: %s\n", gai_strerror(s));
65 return NULL;
66 }
67 return bprintf("%s", host);
68 }
69 }
70
71 freeifaddrs(ifaddr);
72
73 return NULL;
74 }