尝试通过ioctl&SIOCGIFCONF提取IP和MAC
# cat /etc/redhat-release
Red Hat Enterprise Linux Server release 7.0 (Maipo)
# uname -a
Linux *** 3.10.0-123.el7.x86_64 #1 SMP Mon May 5 11:16:57 EDT 2014 x86_64 x86_64 x86_64 GNU/Linux
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define MAX_IFS 64
int main(int argc, char **argv) {
struct ifreq *ifr, *ifend;
struct ifreq ifreq;
struct ifconf ifc;
struct ifreq ifs[MAX_IFS];
int sockfd;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
ifc.ifc_len = sizeof(ifs);
ifc.ifc_req = ifs;
if (ioctl(sockfd, SIOCGIFCONF, &ifc) < 0) {
printf("ioctl(SIOCGIFCONF): %m/n");
return 0;
}
ifend = ifs + (ifc.ifc_len / sizeof(struct ifreq));
for (ifr = ifc.ifc_req; ifr < ifend; ifr++) {
if (ifr->ifr_addr.sa_family == AF_INET) {
//strncpy(ifreq.ifr_name, "ens3",sizeof(ifreq.ifr_name));
strncpy(ifreq.ifr_name, ifr->ifr_name,sizeof(ifreq.ifr_name));
if (ioctl (sockfd, SIOCGIFHWADDR, &ifreq) < 0) {
printf("SIOCGIFHWADDR(%s): %m/n", ifreq.ifr_name);
return 0;
}
printf("\nIp Address %s\t", inet_ntoa( ( (struct sockaddr_in *) &ifr->ifr_addr)->sin_addr));
printf("\nDevice %s -> Ethernet %02x:%02x:%02x:%02x:%02x:%02x\t", ifreq.ifr_name,
(int) ((unsigned char *) &ifreq.ifr_hwaddr.sa_data)[0],
(int) ((unsigned char *) &ifreq.ifr_hwaddr.sa_data)[1],
(int) ((unsigned char *) &ifreq.ifr_hwaddr.sa_data)[2],
(int) ((unsigned char *) &ifreq.ifr_hwaddr.sa_data)[3],
(int) ((unsigned char *) &ifreq.ifr_hwaddr.sa_data)[4],
(int) ((unsigned char *) &ifreq.ifr_hwaddr.sa_data)[5]);
}
}
return 0;
}
运行结果:
Ip Address 127.0.0.1
Device lo -> Ethernet 00:00:00:00:00:00
Ip Address 10.30.16.243
Device ens3 -> Ethernet 06:bf:76:00:0a:8f