lokinet/llarp/net.cpp

122 lines
2.5 KiB
C++
Raw Normal View History

#include "llarp/net.hpp"
2018-02-01 17:06:49 +00:00
#include "str.hpp"
2018-07-24 03:23:00 +00:00
#ifdef ANDROID
2018-07-24 02:34:12 +00:00
#include "android/ifaddrs.h"
2018-07-24 03:21:33 +00:00
#else
#include <ifaddrs.h>
2018-07-24 02:34:12 +00:00
#endif
2018-02-01 17:06:49 +00:00
#include <arpa/inet.h>
2018-07-24 03:21:33 +00:00
2018-05-23 13:49:00 +00:00
#include <net/if.h>
2018-05-18 13:17:58 +00:00
#include <cstdio>
2018-05-29 12:15:34 +00:00
#include "logger.hpp"
2018-02-01 17:07:01 +00:00
bool
operator==(const sockaddr& a, const sockaddr& b)
{
socklen_t sz = sizeof(a.sa_data);
switch(a.sa_family)
{
case AF_INET:
sz = sizeof(sockaddr_in);
break;
case AF_INET6:
sz = sizeof(sockaddr_in6);
break;
default:
break;
}
return a.sa_family == b.sa_family && memcmp(a.sa_data, b.sa_data, sz) == 0;
}
bool
operator<(const sockaddr_in6& a, const sockaddr_in6& b)
{
return memcmp(&a, &b, sizeof(sockaddr_in6)) < 0;
}
bool
operator<(const in6_addr& a, const in6_addr& b)
{
return memcmp(&a, &b, sizeof(in6_addr)) < 0;
}
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;
2018-02-01 17:07:01 +00:00
socklen_t sl = sizeof(sockaddr_in6);
if(af == AF_INET)
sl = sizeof(sockaddr_in);
2018-06-14 20:42:30 +00:00
if(getifaddrs(&ifa) == -1)
return false;
2018-02-01 17:07:01 +00:00
ifaddrs* i = ifa;
while(i)
{
if(i->ifa_addr)
2018-05-18 13:17:58 +00:00
{
// llarp::LogInfo(__FILE__, "scanning ", i->ifa_name, " af: ",
2018-06-08 13:12:17 +00:00
// std::to_string(i->ifa_addr->sa_family));
if(llarp::StrEq(i->ifa_name, ifname) && i->ifa_addr->sa_family == af)
{
2018-07-26 10:21:19 +00:00
// can't do this here
// llarp::Addr a(*i->ifa_addr);
// if(!a.isPrivate())
2018-07-26 10:21:19 +00:00
//{
// llarp::LogInfo(__FILE__, "found ", ifname, " af: ", af);
memcpy(addr, i->ifa_addr, sl);
if(af == AF_INET6)
{
// set scope id
sockaddr_in6* ip6addr = (sockaddr_in6*)addr;
ip6addr->sin6_scope_id = if_nametoindex(ifname);
ip6addr->sin6_flowinfo = 0;
2018-05-23 13:49:00 +00:00
}
found = true;
break;
}
2018-07-26 10:21:19 +00:00
//}
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
}
if(ifa)
freeifaddrs(ifa);
2018-02-01 17:07:01 +00:00
return found;
2018-02-01 17:06:49 +00:00
}
namespace llarp
{
bool
GetBestNetIF(std::string& ifname, int af)
{
ifaddrs* ifa = nullptr;
bool found = false;
if(getifaddrs(&ifa) == -1)
return false;
ifaddrs* i = ifa;
while(i)
{
if(i->ifa_addr)
{
if(i->ifa_addr->sa_family == af)
{
llarp::Addr a(*i->ifa_addr);
if(!(a.isPrivate() || a.isLoopback()))
{
ifname = i->ifa_name;
found = true;
break;
}
}
}
i = i->ifa_next;
}
if(ifa)
freeifaddrs(ifa);
return found;
}
} // namespace llarp