• 利用C语言获取设备的MAC address


    利用C语言获取设备的MAC address


    MAC address --> Medium Access Control layer address

    // 
    // http://www.binarytides.com/c-program-to-get-mac-address-from-interface-name-on-linux/
    
    
    #include <stdio.h>	//printf
    #include <string.h>	//strncpy
    #include <sys/socket.h>
    #include <sys/ioctl.h>
    #include <net/if.h>	//ifreq
    #include <unistd.h>	//close
    
    
    void getmacaddr(char *macaddr, const char *interface)
    {
    	int fd;
    	struct ifreq ifr;
    	const char *iface = interface;
    	unsigned char *mac;
    	
    	fd = socket(AF_INET, SOCK_DGRAM, 0);
    
    	ifr.ifr_addr.sa_family = AF_INET;
    	strncpy(ifr.ifr_name , iface , IFNAMSIZ-1);
    
    	ioctl(fd, SIOCGIFHWADDR, &ifr);
    
    	close(fd);
    	
    	mac = (unsigned char *)ifr.ifr_hwaddr.sa_data;
    	
    	sprintf(macaddr, "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" , mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
    	
    }
    
    int main()
    {
    	char macaddress[17]={'0'};
    	getmacaddr(macaddress, "eth0");
    
    	int i=0;
    	for(i=0;i<sizeof(macaddress);i++)
    	{
    		printf("%c", macaddress[i]);
    	}
    	printf("
    ");
    
    
    	return 0;
    }
    
    

    这里有一个需要玩味的是,函数getmacaddr()同样可以使用二维字符之称char **作为参数,但是需要注意的是,不能直接拿参数来操作,需要设置临时变量。

    void _getmacaddr(char **macaddr, const char *interface)
    {
    	int fd;
    	struct ifreq ifr;
    	const char *iface = interface;
    	unsigned char *mac;
    	char **newaddress = macaddr;
    	
    	fd = socket(AF_INET, SOCK_DGRAM, 0);
    
    	ifr.ifr_addr.sa_family = AF_INET;
    	strncpy(ifr.ifr_name , iface , IFNAMSIZ-1);
    
    	ioctl(fd, SIOCGIFHWADDR, &ifr);
    
    	close(fd);
    	
    	mac = (unsigned char *)ifr.ifr_hwaddr.sa_data;
    	
    	sprintf( *newaddress, "%.2x:%.2x:%.2x:%.2x:%.2x:%.2x" , mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
    	
    }
    
    

    参考:


    1、Get MAC Address
    2、How to get mac address

  • 相关阅读:
    Monggodb基础
    手游运营数据指标
    JSON语法
    Java中日期转换问题
    Java线程中锁的问题
    鼠标移动监听的注意事项
    链接数据库的问题
    获取显示器的宽高
    JTable的使用问题
    JScrollPane控件中添加其他控件的问题&&JScrollPane设置滚动条&&调整滚动速度
  • 原文地址:https://www.cnblogs.com/xuanyuanchen/p/5864710.html
Copyright © 2020-2023  润新知