From: Remi Gacogne Date: Tue, 11 Oct 2022 08:06:07 +0000 (+0200) Subject: Cleaner way of getting the IP/masks associated to a network interface X-Git-Tag: dnsdist-1.8.0-rc1~281^2~1 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=a9be9813635262c7b0ac05f5b7dac6835d67c12d;p=thirdparty%2Fpdns.git Cleaner way of getting the IP/masks associated to a network interface Fixes coverity's report CID 1498958. --- diff --git a/pdns/iputils.cc b/pdns/iputils.cc index 1c25ae5615..d9979b4de2 100644 --- a/pdns/iputils.cc +++ b/pdns/iputils.cc @@ -589,7 +589,7 @@ std::vector getListOfAddressesOfNetworkInterface(const std::string } #if HAVE_GETIFADDRS -static uint8_t convertNetmaskToBits(const struct in_addr* mask, socklen_t len) +static uint8_t convertNetmaskToBits(const uint8_t* mask, socklen_t len) { if (mask == nullptr || len > 128) { throw std::runtime_error("Invalid parameters passed to convertNetmaskToBits"); @@ -598,7 +598,7 @@ static uint8_t convertNetmaskToBits(const struct in_addr* mask, socklen_t len) uint8_t result = 0; // for all bytes in the address (4 for IPv4, 16 for IPv6) for (size_t idx = 0; idx < len; idx++) { - uint8_t byte = *(reinterpret_cast(&mask->s_addr) + idx); + uint8_t byte = *(mask + idx); // count the number of bits set while (byte > 0) { result += (byte & 1); @@ -633,9 +633,16 @@ std::vector getListOfRangesOfNetworkInterface(const std::string& itf) continue; } - auto netmask = reinterpret_cast(ifa->ifa_netmask); - uint8_t maskBits = convertNetmaskToBits(&netmask->sin_addr, addr.getSocklen()); - result.emplace_back(addr, maskBits); + if (ifa->ifa_addr->sa_family == AF_INET) { + auto netmask = reinterpret_cast(ifa->ifa_netmask); + uint8_t maskBits = convertNetmaskToBits(reinterpret_cast(&netmask->sin_addr.s_addr), 4); + result.emplace_back(addr, maskBits); + } + else if (ifa->ifa_addr->sa_family == AF_INET6) { + auto netmask = reinterpret_cast(ifa->ifa_netmask); + uint8_t maskBits = convertNetmaskToBits(reinterpret_cast(&netmask->sin6_addr.s6_addr), 16); + result.emplace_back(addr, maskBits); + } } freeifaddrs(ifaddr);