cache getifaddrs - linux

This commit is contained in:
travis laduke 2023-05-17 07:16:09 -07:00 committed by Travis LaDuke
parent 4192f6a6d9
commit 259ee610a6
2 changed files with 18 additions and 1 deletions

View file

@ -126,12 +126,14 @@ LinuxEthernetTap::LinuxEthernetTap(
_mtu(mtu),
_fd(0),
_enabled(true),
_run(true)
_run(true),
_lastIfAddrsUpdate(0)
{
static std::mutex s_tapCreateLock;
char procpath[128],nwids[32];
struct stat sbuf;
// Create only one tap at a time globally.
std::lock_guard<std::mutex> tapCreateLock(s_tapCreateLock);
@ -438,6 +440,14 @@ bool LinuxEthernetTap::removeIp(const InetAddress &ip)
std::vector<InetAddress> LinuxEthernetTap::ips() const
{
uint64_t now = OSUtils::now();
if ((now - _lastIfAddrsUpdate) <= GETIFADDRS_CACHE_TIME) {
return _ifaddrs;
}
_lastIfAddrsUpdate = now;
struct ifaddrs *ifa = (struct ifaddrs *)0;
if (getifaddrs(&ifa))
return std::vector<InetAddress>();
@ -471,6 +481,8 @@ std::vector<InetAddress> LinuxEthernetTap::ips() const
std::sort(r.begin(),r.end());
r.erase(std::unique(r.begin(),r.end()),r.end());
_ifaddrs = r;
return r;
}

View file

@ -57,6 +57,9 @@ public:
virtual void setMtu(unsigned int mtu);
virtual void setDns(const char *domain, const std::vector<InetAddress> &servers) {}
private:
void (*_handler)(void *,void *,uint64_t,const MAC &,const MAC &,unsigned int,unsigned int,const void *,unsigned int);
void *_arg;
@ -71,6 +74,8 @@ private:
std::atomic_bool _enabled;
std::atomic_bool _run;
std::thread _tapReaderThread;
mutable std::vector<InetAddress> _ifaddrs;
mutable uint64_t _lastIfAddrsUpdate;
};
} // namespace ZeroTier