#include<stdio.h>
#include <sys/ioctl.h>
#include<netinet/in.h>
#include<net/if.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
bool queryLocalIpAddrInfos()
{
int sock;
struct sockaddr_in* addr;
struct ifreq* ifr;
struct ifconf ifc;
char buffer[1024];
const char IFNAME[] = "lo";
uint16_t pub = 0;
uint32_t idc = 0;
sock = socket(AF_INET, SOCK_DGRAM, 0);
printf("create socket:%d\n",sock);
if (sock < 0)
{
printf("queryLocalIpAddrInfos, fail to create socket");
return false;
}
// get all interface
ifc.ifc_len = sizeof(buffer);
ifc.ifc_buf = buffer;
if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0)
{
printf("queryLocalIpAddrInfos, fail to get IF list");
close(sock);
return false;
}
ifr = ifc.ifc_req;
printf("loop times:%lu\n",ifc.ifc_len/sizeof(struct ifreq));
for (int idx = ifc.ifc_len / sizeof(struct ifreq); --idx >= 0; ifr++)
{
printf("ifr->ifr_name:%s\n",ifr->ifr_name);
// skip 'lo'
if (!strcmp(ifr->ifr_name, IFNAME))
continue;
// flags
if (ioctl(sock, SIOCGIFFLAGS, ifr) == -1)
{
printf("queryLocalIpAddrInfos, fail to get flags for interface %s", ifr->ifr_name);
continue;
}
if (ioctl(sock, SIOCGIFADDR, ifr) == -1)
{
printf("queryLocalIpAddrInfos, fail to get ip address for interface %s", ifr->ifr_name);
continue;
}
addr = (struct sockaddr_in *)&(ifr->ifr_addr);
uint32_t m_nLocalIp = addr->sin_addr.s_addr;
printf("m_nLocalIp:%u\n",m_nLocalIp);
// network mask
if (ioctl(sock, SIOCGIFNETMASK, ifr) == -1)
{
printf("queryLocalIpAddrInfos, fail to get network mask for interface %s", ifr->ifr_name);
continue;
}
addr = (struct sockaddr_in *)&(ifr->ifr_addr);
uint32_t m_nNetMask = addr->sin_addr.s_addr;
printf("m_nNetMask:%u\n",m_nNetMask);
break;
} // for
close(sock);
return true;
}
int main()
{
bool bool_value = queryLocalIpAddrInfos();
printf("main:%d\n",bool_value);
return 0;
}