1
1
Fork 0
mirror of https://github.com/oxen-io/lokinet synced 2023-12-14 06:53:00 +01:00

Refactor/fix GetAdaptersAddresses

- We need to pass a flag to get Windows to include gateway info.
- Refactor it to use microsoft's recommended magic default 15000 buffer
  size and repeat in a loop a few times until it works.  Developers,
  developers, developers, developers!
This commit is contained in:
Jason Rhinelander 2022-09-15 00:01:07 -03:00
parent d1e997177d
commit 9097435f64
No known key found for this signature in database
GPG key ID: C4992CE7A88D4262

View file

@ -26,15 +26,24 @@ namespace llarp::net
void void
iter_adapters(Visit_t&& visit, int af = AF_UNSPEC) const iter_adapters(Visit_t&& visit, int af = AF_UNSPEC) const
{ {
ULONG sz{}; ULONG err;
GetAdaptersAddresses(af, 0, nullptr, nullptr, &sz); ULONG sz = 15000; // MS-recommended so that it "never fails", but often fails with a too
auto ptr = std::make_unique<byte_t[]>(sz); // large error.
auto* addrs = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(ptr.get()); std::unique_ptr<byte_t[]> ptr;
PIP_ADAPTER_ADDRESSES addr;
int tries = 0;
do
{
ptr = std::make_unique<byte_t[]>(sz);
addr = reinterpret_cast<PIP_ADAPTER_ADDRESSES>(ptr.get());
err = GetAdaptersAddresses(
af, GAA_FLAG_INCLUDE_GATEWAYS | GAA_FLAG_INCLUDE_PREFIX, nullptr, addr, &sz);
} while (err == ERROR_BUFFER_OVERFLOW and ++tries < 4);
if (auto err = GetAdaptersAddresses(af, 0, nullptr, addrs, &sz); err != ERROR_SUCCESS) if (err != ERROR_SUCCESS)
throw llarp::win32::error{err, "GetAdaptersAddresses()"}; throw llarp::win32::error{err, "GetAdaptersAddresses()"};
for (auto* addr = addrs; addr->Next; addr = addr->Next) for (; addr->Next; addr = addr->Next)
visit(addr); visit(addr);
} }