可以直接寫個程式碼透過 SIOCGIFHWADDR 這個關鍵字,
使用方法 ioctl( SIOCGIFHWADDR );
去Kernel Space得到資訊再傳回User Space
範例如下:
#include <stdio.h>#include <string.h>#include <unistd.h>#include <net/if.h>#include <sys/ioctl.h>#include <sys/types.h>#include <sys/socket.h>int GetMac( const char *ifname, unsigned char *mac ){ int sock, ret; struct ifreq ifr; sock = socket( AF_INET, SOCK_STREAM, 0 ); if ( sock < 0 ) { perror( "socket" ); return -1; } memset( &ifr, 0, sizeof(ifr) ); strcpy( ifr.ifr_name, ifname ); ret = ioctl( sock, SIOCGIFHWADDR, &ifr, sizeof(ifr) ); if ( ret == 0 ) { memcpy( mac, ifr.ifr_hwaddr.sa_data, 6 ); } else { perror( "ioctl" ); } close( sock ); return ret;}int main( int argc, char **argv ){ int ret; char ifname[IFNAMSIZ]; unsigned char mac[6]; if ( argc == 1 ) { strcpy( ifname, "eth0" ); } else { strcpy( ifname, argv[1] ); } memset( mac, 0, sizeof(mac) ); ret = GetMac( ifname, mac ); if ( ret == 0 ) { printf( "%s mac address is: [%02X:%02X:%02X:%02X:%02X:%02X]\n", ifname, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5] ); } else { fprintf( stderr, "Can't get %s's mac address\n", ifname ); } return 0;}
沒有留言:
張貼留言