#include<stdio.h>#include<ifaddrs.h>#include<string.h>#include<arpa/inet.h>intmain(int argc,constchar* argv[]){structifaddrs* ifAddrStruct=NULL;structifaddrs* ifa=NULL;void* tmpAddrPtr=NULL;getifaddrs(&ifAddrStruct);for(ifa = ifAddrStruct; ifa !=NULL; ifa = ifa->ifa_next){if(!ifa->ifa_addr){continue;}if(ifa->ifa_addr->sa_family == AF_INET){// check it is IP4// is a valid IP4 Address
tmpAddrPtr=&((structsockaddr_in*)ifa->ifa_addr)->sin_addr;char addressBuffer[INET_ADDRSTRLEN];inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer);}elseif(ifa->ifa_addr->sa_family == AF_INET6){// check it is IP6// is a valid IP6 Address
tmpAddrPtr=&((structsockaddr_in6*)ifa->ifa_addr)->sin6_addr;char addressBuffer[INET6_ADDRSTRLEN];inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);printf("%s IPv6 Address %s\n", ifa->ifa_name, addressBuffer);}}if(ifAddrStruct!=NULL)freeifaddrs(ifAddrStruct);return0;}