Xinqi Bao's Git

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