Linux下socket编程获取本机网卡mac地址

不管网卡up与否,只要注册了网卡,如eth0,那么就可通过命令字 SIOCGIFHWADDR 获取本机的mac地址。

#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>
 
int getmac(char * mac, char *ifname)
{
	struct ifreq ifreq;
	int fd;
 
	if ((fd = socket (AF_INET, SOCK_STREAM, 0)) < 0)
	{
		perror ("socket");
		return -1;
	}
	strcpy (ifreq.ifr_name, ifname);    //Currently, only get eth0

	if (ioctl (fd, SIOCGIFHWADDR, &ifreq) < 0)
	{
		close(fd);
		perror ("SIOCGIFHWADDR");
		return -1;
	}
	close(fd);
	sprintf(mac,"%02x:%02x:%02x:%02x:%02x:%02x",
            (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;
}
 
int main(int argc, char *argv[])
{
	char mac[30];
	int ret;
	char ifname[10] = {0};
	
	if (argc < 2) {
		fprintf(stderr, "too few arguments!\n");
		return -1;
	}
	
	memcpy(ifname, argv[1], strlen(argv[1]));
	
	ret = getmac(mac, ifname);
	if(ret)
	{
		fprintf(stderr, "getmac failed\n");
		return -1;
	}
	
	fprintf(stdout, "ifname[%s], Mac addr:%s\n", ifname, mac);
	
    return 0;
}

编译代码并执行获取eth0的网卡Mac地址

mhp0114@mhp0114-virtual-machine:~/workspace/share/test$ gcc getmac.c -o getmac
mhp0114@mhp0114-virtual-machine:~/workspace/share/test$ ./getmac eth0
ifname[eth0], Mac addr:00:0c:29:23:ca:ec

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页