Linux C 获取本机所有网卡的 IP,Mask
0 运行环境
-
本机系统:Windows 10
-
虚拟机软件:Oracle VM VirtualBox 6
-
虚拟机系统:Ubuntu 18
1 代码
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
int get_localIPAndMask(char *ip,char *mask)
{
int fd, intrface, retn = 0;
struct ifreq buf[INET_ADDRSTRLEN];
struct ifconf ifc;
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) >= 0)
{
ifc.ifc_len = sizeof(buf);
// caddr_t,Linux内核源码里定义的:typedef void *caddr_t;
ifc.ifc_buf = (caddr_t)buf;
if (!ioctl(fd, SIOCGIFCONF, (char *)&ifc))
{
intrface = ifc.ifc_len/sizeof(struct ifreq);
while (intrface-- > 0)
{
if (!(ioctl(fd, SIOCGIFADDR, (char *)&buf[intrface])))
{
ip = (inet_ntoa(((struct sockaddr_in*)(&buf[intrface].ifr_addr))->sin_addr));
printf("IP:%s\n", ip);
}
if (!(ioctl(fd, SIOCGIFNETMASK, (char *)&buf[intrface])))
{
mask = (inet_ntoa(((struct sockaddr_in*)(&buf[intrface].ifr_addr))->sin_addr));
printf("mask:%s\n", mask);
}
}
}
close(fd);
return 0;
}
}
int main()
{
char ip[64];
memset(ip, 0, sizeof(ip));
char mask[64];
memset(mask, 0, sizeof(mask));
get_localIPAndMask(ip,mask);
return 0;
}
2 运行结果
与 ifconfig 验证一致,成功: