Xinqi Bao's Git

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