Ifa_addr returning subnet mask instead of interface IP

I'm building an ipk for OpenWRT 24.10.0 that reads the interface IPs and does something with that information. The source code is written in c++, using g++ 9.4.0 and openwrt-sdk-24.10.0-octeon-generic_gcc-13.3.0_musl.Linux-x86_64 to build.

For some reason, the following code:

struct ifaddrs *ifap, *ifa;
getifaddrs(&ifap);
if(ifap)
{
for(ifa = ifap; ifa; ifa = ifa->ifa_next)
{
if(ifa->ifa_addr && ifa->ifa_addr->sa_family==AF_INET)
{
printf("%s:%s %s\n", ifa->ifa_name, inet_ntoa(((struct sockaddr_in*)ifa->ifa_addr)->sin_addr), inet_ntoa(((struct sockaddr_in*)ifa->ifa_netmask)->sin_addr));
}
}
}

prints out

lan0:255.255.255.0 255.255.255.0

lan0 should be 192.198.1.123 with subnet mask 255.255.255.0

Any idea what's wrong? Is this version of g++ or sdk bugged?

man inet_ntoa says

The inet_ntoa() function converts the Internet host address in, given in network byte order, to a string in IPv4 dotted-decimal notation. The string is returned in a statically allocated buffer, which sub‐sequent calls will overwrite.

You could split the output in two printf calls, or convert and copy the strings before calling printf, or use some other string conversion function.

This works for me:


#include <arpa/inet.h>
#include <netinet/in.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>

int main(int argc, char **argv)
{
	struct ifaddrs *ifap, *ifa;
	getifaddrs(&ifap);
	if(ifap)
	{
		for(ifa = ifap; ifa; ifa = ifa->ifa_next)
		{
			if(ifa->ifa_addr && ifa->ifa_addr->sa_family==AF_INET)
			{
				printf("%s:%s",  ifa->ifa_name, inet_ntoa(((struct sockaddr_in*)ifa->ifa_addr)->sin_addr));
				printf(" %s\n",inet_ntoa(((struct sockaddr_in*)ifa->ifa_netmask)->sin_addr));
			}
		}
	}
	return 0;
}

No wonder! Thanks for the solution!