红联Linux门户
Linux帮助

获取linux机器上的网卡地址

发布时间:2017-04-05 11:41:39来源:linux网站作者:SurfUniverse
获取linux机器上的网卡地址的代码如下:
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <unistd.h>
int get_mac(char* in_mac, int size)
{
struct ifreq ifr;
struct ifconf ifc;
char buf[1024];
unsigned char mac[6];
int success = 0;
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == -1) { /* handle error*/ };
ifc.ifc_len = sizeof(buf);
ifc.ifc_buf = buf;
if (ioctl(sock, SIOCGIFCONF, &ifc) == -1) { /* handle error */ }
struct ifreq* it = ifc.ifc_req;
const struct ifreq* const end = it + (ifc.ifc_len / sizeof(struct ifreq));
for (; it != end; ++it) {
strcpy(ifr.ifr_name, it->ifr_name);
if (ioctl(sock, SIOCGIFFLAGS, &ifr) == 0) {
if (! (ifr.ifr_flags & IFF_LOOPBACK)) { // don't count loopback
if (ioctl(sock, SIOCGIFHWADDR, &ifr) == 0) {
memcpy(mac, ifr.ifr_hwaddr.sa_data, 6);
snprintf(in_mac, size, "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n" , mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
success = 1;
break;
}
}
}
}
return success;
}
int main()
{
char mac[32];
bzero(mac, sizeof(mac));
if (get_mac(mac, 32)) {
printf(mac);
}
return 0;
}
 
运行效果:
获取linux机器上的网卡地址
 
本文永久更新地址:http://www.linuxdiyf.com/linux/29747.html