LINUX中获取MAC地址的方法

看到经常有人问如何在linux中获取MAC地址,我干脆把代码贴出来,方法就是用ioctl( SIOCGIFHWADDR );

#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;
}

# 1
好,留个记号
# 2
好像有错误
wany031123 at 2007-10-19 > top of Msdn China Tech,专题开发,技术,项目,网络通信...
# 3
只能取自己机子的MAC没什么用
(程序类型定义中间的空格一个都没有,要自己加上)
stoneme at 2007-10-19 > top of Msdn China Tech,专题开发,技术,项目,网络通信...
# 4
正在找,谢谢哈,不过现在好累啊,休息了,明天看~~~:)
philions-左手写字 at 2007-10-19 > top of Msdn China Tech,专题开发,技术,项目,网络通信...