可以直接寫個程式碼透過 SIOCGIFHWADDR 這個關鍵字,
使用方法 ioctl( SIOCGIFHWADDR );
去Kernel Space得到資訊再傳回User Space
範例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
#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 <strong>GetMac</strong>( 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 <strong>main</strong>( 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; } |