Skip to content

Commit 9dc5753

Browse files
authored
Merge pull request #464 from correabuscar/osx_replace__getnameinfo__with__inet_ntop
osx: replace getnameinfo with inet_ntop
2 parents 2512364 + f4eea3f commit 9dc5753

File tree

1 file changed

+21
-8
lines changed

1 file changed

+21
-8
lines changed

src/osx/btop_collect.cpp

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ tab-size = 4
4141
#include <sys/statvfs.h>
4242
#include <sys/sysctl.h>
4343
#include <sys/types.h>
44+
#include <netinet/in.h> // for inet_ntop
4445
#include <unistd.h>
4546
#include <stdexcept>
4647

@@ -863,7 +864,9 @@ namespace Net {
863864
return empty_net;
864865
}
865866
int family = 0;
866-
char ip[NI_MAXHOST];
867+
static_assert(INET6_ADDRSTRLEN >= INET_ADDRSTRLEN); // 46 >= 16, compile-time assurance.
868+
enum { IPBUFFER_MAXSIZE = INET6_ADDRSTRLEN }; // manually using the known biggest value, guarded by the above static_assert
869+
char ip[IPBUFFER_MAXSIZE];
867870
interfaces.clear();
868871
string ipv4, ipv6;
869872

@@ -884,16 +887,26 @@ namespace Net {
884887
}
885888
//? Get IPv4 address
886889
if (family == AF_INET) {
887-
if (net[iface].ipv4.empty() and
888-
getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), ip, NI_MAXHOST, NULL, 0, NI_NUMERICHOST) == 0)
889-
net[iface].ipv4 = ip;
890+
if (net[iface].ipv4.empty()) {
891+
if (NULL != inet_ntop(family, &(reinterpret_cast<struct sockaddr_in*>(ifa->ifa_addr)->sin_addr), ip, IPBUFFER_MAXSIZE)) {
892+
net[iface].ipv4 = ip;
893+
} else {
894+
int errsv = errno;
895+
Logger::error("Net::collect() -> Failed to convert IPv4 to string for iface " + string(iface) + ", errno: " + strerror(errsv));
896+
}
897+
}
890898
}
891899
//? Get IPv6 address
892900
else if (family == AF_INET6) {
893-
if (net[iface].ipv6.empty() and
894-
getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in6), ip, NI_MAXHOST, NULL, 0, NI_NUMERICHOST) == 0)
895-
net[iface].ipv6 = ip;
896-
}
901+
if (net[iface].ipv6.empty()) {
902+
if (NULL != inet_ntop(family, &(reinterpret_cast<struct sockaddr_in6*>(ifa->ifa_addr)->sin6_addr), ip, IPBUFFER_MAXSIZE)) {
903+
net[iface].ipv6 = ip;
904+
} else {
905+
int errsv = errno;
906+
Logger::error("Net::collect() -> Failed to convert IPv6 to string for iface " + string(iface) + ", errno: " + strerror(errsv));
907+
}
908+
}
909+
} // else, ignoring family==AF_LINK (see man 3 getifaddrs)
897910
}
898911

899912
unordered_flat_map<string, std::tuple<uint64_t, uint64_t>> ifstats;

0 commit comments

Comments
 (0)