linux下C语言读取网卡MAC地址

#include 
#include
#include <string.h>
#include
#include
#include
#include in.h>
#include if.h>

int main(int argc, char *argv[])
{
struct ifreq ifreq;
int sock = 0;
char mac[32] = "";

if(argc < 2){
printf("Usage: ./main eth0");
return 1;
}

sock = socket(AF_INET,SOCK_STREAM,0);
if(sock < 0)
{
perror("error sock");
return 2;
}

strcpy(ifreq.ifr_name,argv[1]);
if(ioctl(sock,SIOCGIFHWADDR,&ifreq) < 0)
{
perror("error ioctl");
return 3;
}

int i = 0;
for(i = 0; i < 6; i++){
sprintf(mac+3*i, "%02X:", (unsigned char)ifreq.ifr_hwaddr.sa_data[i]);
}
mac[strlen(mac) - 1] = 0;
printf("MAC: %s\n", mac);

return 0;
}

 

输入:./mac eth0

显示eth0的MAC地址.

转载于:https://www.cnblogs.com/hnrainll/archive/2012/01/17/2324967.html

你可能感兴趣的:(c/c++,操作系统)