I feel that there is a problem with inet_ntoa printing subnet mask under Linux. This program can output correctly on Mac system.
I wrote a function myself that can output the correct result.
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <sstream>
using namespace std;
string getip(const sockaddr_in* addr)
{
ostringstream s;
int a = ntohl(addr->sin_addr.s_addr);
s << ((a >> 24) & 0xFF) << '.' << ((a >> 16) & 0xFF) << '.'
<< ((a >> 8) & 0xFF) << '.' << (a & 0xFF);
return s.str();
}
int main(void)
{
struct ifaddrs* myaddrs;
struct sockaddr_in *ss, *kk;
char buf[100];
if (getifaddrs(&myaddrs) == 0) {
for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) {
ss = (struct sockaddr_in*) ifa->ifa_addr;
kk = (struct sockaddr_in*) ifa->ifa_netmask;
if (ss->sin_family == AF_INET)
cout << ifa->ifa_name << ":" << getip(ss) << " netmask:" << getip(kk) << endl;
}
}
return 0;
}
I feel that there is a problem with inet_ntoa printing subnet mask under Linux. This program can output correctly on Mac system.
I wrote a function myself that can output the correct result.
Use the
inet_ntop
function to get the correct result