@@ -41,6 +41,7 @@ tab-size = 4
41
41
#include < sys/statvfs.h>
42
42
#include < sys/sysctl.h>
43
43
#include < sys/types.h>
44
+ #include < netinet/in.h> // for inet_ntop
44
45
#include < unistd.h>
45
46
#include < stdexcept>
46
47
@@ -863,7 +864,9 @@ namespace Net {
863
864
return empty_net;
864
865
}
865
866
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];
867
870
interfaces.clear ();
868
871
string ipv4, ipv6;
869
872
@@ -884,16 +887,26 @@ namespace Net {
884
887
}
885
888
// ? Get IPv4 address
886
889
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
+ }
890
898
}
891
899
// ? Get IPv6 address
892
900
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)
897
910
}
898
911
899
912
unordered_flat_map<string, std::tuple<uint64_t , uint64_t >> ifstats;
0 commit comments