Xinqi Bao's Git

25071e46f2f93c4cdc63dfd2168aa27648e1fc52
[slstatus.git] / components / ip.c
1 /* See LICENSE file for copyright and license details. */
2 #if defined(__linux__)
3 #include <err.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 warn("Failed to get IPv4 address for interface %s", iface);
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 warnx("Failed to get IPv4 address for interface %s", iface);
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 warn("Failed to get IPv6 address for interface %s", iface);
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 warnx("Failed to get IPv6 address for interface %s", iface);
62 return NULL;
63 }
64 return bprintf("%s", host);
65 }
66 }
67
68 freeifaddrs(ifaddr);
69
70 return NULL;
71 }
72 #endif