2017-09-17 23:45:03 +08:00
|
|
|
/* See LICENSE file for copyright and license details. */
|
2018-03-29 01:46:27 +08:00
|
|
|
#include <errno.h>
|
2017-09-17 22:18:17 +08:00
|
|
|
#include <ifaddrs.h>
|
|
|
|
#include <netdb.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <string.h>
|
2018-05-02 14:21:32 +08:00
|
|
|
#if defined(__OpenBSD__)
|
2018-05-07 17:21:59 +08:00
|
|
|
#include <sys/types.h>
|
|
|
|
#include <sys/socket.h>
|
2018-05-02 14:21:32 +08:00
|
|
|
#endif
|
2017-09-17 22:18:17 +08:00
|
|
|
|
2017-09-24 21:33:01 +08:00
|
|
|
#include "../util.h"
|
2017-09-17 22:18:17 +08:00
|
|
|
|
2018-05-19 19:34:18 +08:00
|
|
|
static const char *
|
|
|
|
ip(const char *iface, unsigned short sa_family)
|
2017-09-17 22:18:17 +08:00
|
|
|
{
|
|
|
|
struct ifaddrs *ifaddr, *ifa;
|
|
|
|
int s;
|
|
|
|
char host[NI_MAXHOST];
|
|
|
|
|
2018-05-07 04:28:56 +08:00
|
|
|
if (getifaddrs(&ifaddr) < 0) {
|
2018-05-18 16:59:05 +08:00
|
|
|
warn("getifaddrs:");
|
2017-09-17 22:18:17 +08:00
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
|
|
|
|
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
|
2018-05-07 04:28:56 +08:00
|
|
|
if (!ifa->ifa_addr) {
|
2017-09-17 22:18:17 +08:00
|
|
|
continue;
|
|
|
|
}
|
2018-05-19 19:34:18 +08:00
|
|
|
s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in6),
|
|
|
|
host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
|
2018-05-07 04:28:56 +08:00
|
|
|
if (!strcmp(ifa->ifa_name, iface) &&
|
2018-05-19 19:34:18 +08:00
|
|
|
(ifa->ifa_addr->sa_family == sa_family)) {
|
2018-05-20 21:53:48 +08:00
|
|
|
freeifaddrs(ifaddr);
|
2017-09-17 22:18:17 +08:00
|
|
|
if (s != 0) {
|
2018-05-18 16:59:05 +08:00
|
|
|
warn("getnameinfo: %s", gai_strerror(s));
|
2017-09-17 22:18:17 +08:00
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
return bprintf("%s", host);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
freeifaddrs(ifaddr);
|
|
|
|
|
|
|
|
return NULL;
|
|
|
|
}
|
|
|
|
|
|
|
|
const char *
|
2018-05-19 19:34:18 +08:00
|
|
|
ipv4(const char *iface)
|
2017-09-17 22:18:17 +08:00
|
|
|
{
|
2018-05-19 19:34:18 +08:00
|
|
|
return ip(iface, AF_INET);
|
|
|
|
}
|
2017-09-17 22:18:17 +08:00
|
|
|
|
2018-05-19 19:34:18 +08:00
|
|
|
const char *
|
|
|
|
ipv6(const char *iface)
|
|
|
|
{
|
|
|
|
return ip(iface, AF_INET6);
|
2017-09-17 22:18:17 +08:00
|
|
|
}
|