Linux系統(tǒng)下用C語言獲取MAC地址
最近在做一個小程序,需要用到在linux系統(tǒng)里編寫C程序從而獲取MAC地址,從網(wǎng)上搜了一遍,想總結(jié)一下。如果你就只需要單個功能的程序,可以采用方法一,見代碼1,一般最好能夠封裝起來,寫成獲取MAC地址的函數(shù)再調(diào)用,可以采用方法二,見代碼2。
#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; }
將代碼寫入一個C文件,名稱隨便取,姑且存為MAC_addr.c。
在linux下運(yùn)行:gcc -o MAC_addr MAC_addr.c
下一條指令要十分注意,這個函數(shù)是帶參數(shù)才能執(zhí)行的,可以用以下指令:
./MAC_addr etho 即可獲得MAC地址。
想用封裝的形式,寫成一個求MAC地址的函數(shù),然后再調(diào)用此函數(shù),可以用方法二,見代碼2。
代碼2:
#include <stdio.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <net/if.h> //for struct ifreq int get_mac(char * mac, int len_limit) //返回值是實(shí)際寫入char * mac的字符個數(shù)(不包括'\0') { struct ifreq ifreq; int sock; if ((sock = socket (AF_INET, SOCK_STREAM, 0)) < 0) { perror ("socket"); return -1; } strcpy (ifreq.ifr_name, "eth0"); //Currently, only get eth0 if (ioctl (sock, SIOCGIFHWADDR, &ifreq) < 0) { perror ("ioctl"); return -1; } return snprintf (mac, len_limit, "%X:%X:%X:%X:%X:%X", (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]); } int main() { char szMac[18]; int nRtn = get_mac(szMac, sizeof(szMac)); if(nRtn > 0) { fprintf(stderr, "MAC ADDR: %s\n", szMac); } return 0; }
將代碼寫入一個C文件,姑且存為MAC_addr.c。
在linux下運(yùn)行:gcc -o MAC_addr MAC_addr.c
./MAC_addr 即可獲得MAC地址。
親測以上方法都是通過的,歡迎討論是否還有更好的方法!
*博客內(nèi)容為網(wǎng)友個人發(fā)布,僅代表博主個人觀點(diǎn),如有侵權(quán)請聯(lián)系工作人員刪除。