歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux服務器

linux用C語言讀取網卡MAC地址

想獲取硬盤和CPU的序列號,看了hdparm源碼,編譯後運行,可是沒能獲取到硬盤的序列號,那就試試讀網卡的MAC地址了,這是在網上找到的代碼。

     #include <stdio.h>
#include <sys ioctl.h>
#include <sys socket.h>
#include <netinet in.h>
#include <NET if.h>
#include <string.h>

int main(int argc, char *argv[])
{

struct ifreq ifreq;
int sock;

if(argc!=2)
{
printf("Usage : ethname\n");
return 1;
}
if((sock=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("socket");
return 2;
}
strcpy(ifreq.ifr_name,argv[1]);
if(ioctl(sock,SIOCGIFHWADDR,&ifreq)<0)
{
perror("ioctl");
return 3;
}
printf("%02x:%02x:%02x:%02x:%02x:%02x\n",
(unsigned char)ifreq.ifr_hwaddr.sa_data[0],
(unsigned char)ifreq.ifr_hwaddr.sa_data[1],
(unsigned char)ifreq.ifr_hwaddr.sa_data[2],
(unsigned char)ifreq.ifr_hwaddr.sa_data[3],
(unsigned char)ifreq.ifr_hwaddr.sa_data[4],
(unsigned char)ifreq.ifr_hwaddr.sa_data[5]);
return 0;
}

Copyright © Linux教程網 All Rights Reserved