use inet_ntop instead of getnameinfo

saves 979 bytes of reserved buffer because:
NI_MAXHOST is 1025 bytes
and
INET6_ADDRSTRLEN is 46

Depends on PR #457 being merged first.
This commit is contained in:
correabuscar 2022-11-04 04:49:12 +01:00
parent 6fc58c4360
commit 96a22b4078
1 changed files with 31 additions and 7 deletions

View File

@ -26,6 +26,8 @@ tab-size = 4
#include <netdb.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <arpa/inet.h> // for inet_ntop()
#if !(defined(STATIC_BUILD) && defined(__GLIBC__))
#include <pwd.h>
@ -1388,7 +1390,13 @@ namespace Net {
return empty_net;
}
int family = 0;
char ip[NI_MAXHOST];
static_assert(INET6_ADDRSTRLEN >= INET_ADDRSTRLEN); // 46 >= 16, compile-time assurance.
#if defined(IPBUFFER_MAXSIZE)
#error Overwriting a previous macro with the same name: IPBUFFER_MAXSIZE, this means you likely need to rename this one here!
#else
#define IPBUFFER_MAXSIZE (INET6_ADDRSTRLEN) // manually using the known biggest value, guarded by the above static_assert
#endif
char ip[IPBUFFER_MAXSIZE];
interfaces.clear();
string ipv4, ipv6;
@ -1410,19 +1418,35 @@ namespace Net {
net[iface].ipv6.clear();
}
//? Get IPv4 address
if (family == AF_INET) {
if (net[iface].ipv4.empty() and
getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), ip, NI_MAXHOST, NULL, 0, NI_NUMERICHOST) == 0)
net[iface].ipv4 = ip;
if (net[iface].ipv4.empty()) {
if (NULL != inet_ntop(family, &(reinterpret_cast<struct sockaddr_in*>(ifa->ifa_addr)->sin_addr), ip, IPBUFFER_MAXSIZE)) {
net[iface].ipv4 = ip;
} else {
int errsv = errno;
Logger::error("Net::collect() -> Failed to convert IPv4 to string for iface " + string(iface) + ", errno: " + strerror(errsv));
}
}
}
//? Get IPv6 address
else if (family == AF_INET6) {
if (net[iface].ipv6.empty() and
getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in6), ip, NI_MAXHOST, NULL, 0, NI_NUMERICHOST) == 0)
net[iface].ipv6 = ip;
if (net[iface].ipv6.empty()) {
if (NULL != inet_ntop(family, &(reinterpret_cast<struct sockaddr_in6*>(ifa->ifa_addr)->sin6_addr), ip, IPBUFFER_MAXSIZE)) {
net[iface].ipv6 = ip;
} else {
int errsv = errno;
Logger::error("Net::collect() -> Failed to convert IPv6 to string for iface " + string(iface) + ", errno: " + strerror(errsv));
}
}
} //else, ignoring family==AF_PACKET (see man 3 getifaddrs) which is the first one in the `for` loop.
}
#if defined(IPBUFFER_MAXSIZE)
#undef IPBUFFER_MAXSIZE
#else
#error whoa, the programmer forgot something, eg. was this renamed?
#endif
//? Get total recieved and transmitted bytes + device address if no ip was found
for (const auto& iface : interfaces) {