我们有时候会有获取网口的IP和MAC地址的需求。可以通过ioctl来获取。
#include <sys/ioctl.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
void main(void)
{
struct ifreq ifr;
struct ifconf ifc;
char buff[1024];
int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP);
ifc.ifc_len = sizeof(buff);
ifc.ifc_buf = buff;
ioctl(fd, SIOCGIFCONF, &ifc);//获取所有的网口信息
struct ifreq *it = ifc.ifc_req;
const struct ifreq* const end = it + ifc.ifc_len/sizeof(struct ifreq);
for (; it != end; it++)//遍历网口
{
strncpy(ifr.ifr_name, it->ifr_name, strlen(it->ifr_name) + 1);//网口名称,如“eth0”“ra0”
printf("ifr_name :%s\n", ifr.ifr_name);
if (ioctl(fd, SIOCGIFFLAGS, &ifr) == 0)
{
if (!(ifr.ifr_flags & IFF_LOOPBACK))//忽略lo
{
if (ioctl(fd, SIOCGIFHWADDR, &ifr) == 0)//获取MAC
{
unsigned char mac[6];
memcpy(mac, ifr.ifr_hwaddr.sa_data, 6);
printf("mac: %02x:%02x:%02x:%02x:%02x:%02x\n",mac[0],mac[1],mac[2],mac[3], mac[4], mac[5]);
}
if (ioctl(fd, SIOCGIFADDR, &ifr) == 0)//获取IP
{
struct sockaddr_in sin;
memcpy(&sin, &ifr.ifr_addr, sizeof(struct sockaddr_in));
printf("ip: %s\n", inet_ntoa(sin.sin_addr));
}
}
}
}
}
运行结果如下: