Linux system call getifaddr c++
in my c++ application I've wrriten t开发者_如何学运维his code:
struct ifaddrs *ifap;
if (0 != getifaddrs(&ifap)) {
error = errno;
return -1;
}
addresses.clear();
for (struct ifaddrs *ifa = ifap; ifa; ifa = ifa->ifa_next) {
sockaddr *s=ifa->ifa_addr;
PRINT(" LocalIP sockaddr %u.%u.%u.%u \n",s->sa_data[2],s->sa_data[3],s->sa_data[4],s->sa_data[5]);}
when I debug the print I see that when I have static ip like 10.0.0.12 it prints it correct. but ip from DHCP like 192.168.14.12 it prints it "-64.-88.14.12"
how can I solve this issue?
10x
Change %d's to %hhu's.
%d is signed integer. %u is unsigned integer. %hhu is unsigned char.
This code shows why:
#include <cstdio>
int main()
{
char i = 192;
printf("%u, %hhu, %d", i,i,i);
}
Output: 4294967232, 192, -64
Seems like it's trying to print bytes as signed. Try using %u instead of %d inside IP address.
精彩评论