lokinet/llarp/net.cpp

36 lines
762 B
C++
Raw Normal View History

2018-05-17 20:00:58 +00:00
#include <llarp/net.h>
2018-02-01 17:06:49 +00:00
#include "str.hpp"
#include <arpa/inet.h>
2018-02-01 17:07:01 +00:00
#include <ifaddrs.h>
2018-05-18 13:17:58 +00:00
#include <cstdio>
2018-02-01 17:07:01 +00:00
2018-05-17 20:00:58 +00:00
extern "C" {
bool llarp_getifaddr(const char * ifname, int af, struct sockaddr* addr) {
2018-02-01 17:07:01 +00:00
ifaddrs* ifa = nullptr;
bool found = false;
socklen_t sl = sizeof(sockaddr_in6);
if (af == AF_INET) sl = sizeof(sockaddr_in);
2018-05-18 13:17:58 +00:00
if (af == AF_PACKET) sl = sizeof(sockaddr_ll);
2018-02-01 17:06:49 +00:00
2018-02-01 17:07:01 +00:00
if (getifaddrs(&ifa) == -1) return false;
ifaddrs* i = ifa;
while (i) {
2018-05-18 13:17:58 +00:00
if (i->ifa_addr)
{
if (llarp::StrEq(i->ifa_name, ifname) && i->ifa_addr->sa_family == af) {
memcpy(addr, i->ifa_addr, sl);
addr->sa_family = af;
found = true;
break;
}
2018-02-01 17:06:49 +00:00
}
2018-02-01 17:07:01 +00:00
i = i->ifa_next;
2018-02-01 17:06:49 +00:00
}
2018-02-01 17:07:01 +00:00
if (ifa) freeifaddrs(ifa);
return found;
2018-02-01 17:06:49 +00:00
}
2018-05-17 20:00:58 +00:00
}