zoukankan      html  css  js  c++  java
  • 利用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

  • 相关阅读:
    魅族Java面经
    笔试常考的Java基础
    笔试常考的Linux命令大全
    Spring概念
    Java三大框架的配置
    Myeclipse的使用
    项目经验
    Android四大组件及activity的四大启动模式
    java基础
    IT在线笔试总结(二)
  • 原文地址:https://www.cnblogs.com/xuanyuanchen/p/5864710.html
Copyright © 2011-2022 走看看