Xinqi Bao's Git

686344b701175f66d94c6e0510a497b1ad14472f
[slstatus.git] / components / ip.c
1 /* See LICENSE file for copyright and license details. */
2 #if defined(__linux__)
3 #include <errno.h>
4 #include <ifaddrs.h>
5 #include <netdb.h>
6 #include <stdio.h>
7 #include <string.h>
8
9 #include "../util.h"
10
11 const char *
12 ipv4(const char *iface)
13 {
14 struct ifaddrs *ifaddr, *ifa;
15 int s;
16 char host[NI_MAXHOST];
17
18 if (getifaddrs(&ifaddr) == -1) {
19 fprintf(stderr, "getifaddrs: %s\n", strerror(errno));
20 return NULL;
21 }
22
23 for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
24 if (ifa->ifa_addr == NULL) {
25 continue;
26 }
27 s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
28 if ((strcmp(ifa->ifa_name, iface) == 0) && (ifa->ifa_addr->sa_family == AF_INET)) {
29 if (s != 0) {
30 fprintf(stderr, "getnameinfo: %s\n", gai_strerror(s));
31 return NULL;
32 }
33 return bprintf("%s", host);
34 }
35 }
36
37 freeifaddrs(ifaddr);
38
39 return NULL;
40 }
41
42 const char *
43 ipv6(const char *iface)
44 {
45 struct ifaddrs *ifaddr, *ifa;
46 int s;
47 char host[NI_MAXHOST];
48
49 if (getifaddrs(&ifaddr) == -1) {
50 fprintf(stderr, "getifaddrs: %s\n", strerror(errno));
51 return NULL;
52 }
53
54 for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
55 if (ifa->ifa_addr == NULL) {
56 continue;
57 }
58 s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in6), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
59 if ((strcmp(ifa->ifa_name, iface) == 0) && (ifa->ifa_addr->sa_family == AF_INET6)) {
60 if (s != 0) {
61 fprintf(stderr, "getnameinfo: %s\n", gai_strerror(s));
62 return NULL;
63 }
64 return bprintf("%s", host);
65 }
66 }
67
68 freeifaddrs(ifaddr);
69
70 return NULL;
71 }
72 #endif