取得接口對應的MAC地址

#include <stdio.h>   
#include <string.h>   
#include <stdlib.h>   
#include <unistd.h>          
#include <sys/socket.h>   
#include <sys/ioctl.h>   
#include <net/if.h>   
#include <sys/types.h>

#define IFNAMSIZ 16
#define ETH_ALEN 6
#define HWADDR_STR_LEN 18

struct ifinfo
{
  char 		name[IFNAMSIZ];		/* network interface name */
  char 		hwaddr[ETH_ALEN];	/* network interface MAC address */
};


char *hwaddr_to_str(unsigned char *ha);
void hexNumToStr(unsigned int number ,char *str);
int Get_Mac_Address(struct ifinfo *pNetIf);


int main(int argc, char *argv[])
{
	int c;		 
	struct ifinfo pNetIf;

	if ( argc < 3 )  
     {  
        printf("Please input two arguments and try it again! such as "-i eth0"\n");  
        return 0;  
     } 

	while (( c = getopt(argc, argv, "i:")) != -1)  
        {  
                switch(c){  
                case 'i':  
                        printf("The interface is %s.\n", optarg);  
                        memcpy(pNetIf.name, optarg , strlen(optarg)+1);   
						printf("pNetIf.name is %s.\n",pNetIf.name);
						break;  
                case '?':  
                         printf("Please input two arguments and try it again!\n");  
                         break;  
                }  
        } 
	
	if (0 == (Get_Mac_Address(&pNetIf)))
		; 
	else 
		printf("Get MAC address error!");	
	
	return 0;
}

int Get_Mac_Address(struct ifinfo *pNetIf)
{
	struct ifreq ifr;  
    int     sock;  
  
    memset(&ifr, 0, sizeof(struct ifreq));

	sock = socket(AF_INET, SOCK_DGRAM, 0);  
    if(sock < 0)  
      {  
                perror("socket: Unable to open\n");  
                return (-1);  
      }  
  
     memcpy(ifr.ifr_name, pNetIf->name , strlen(pNetIf->name)+1);            

  	//Get MAC address
	if (ioctl(sock, SIOCGIFHWADDR, &ifr) != 0)
	{
		perror("ioctl: SIOCGIFHWADDR");
		close(sock);
		return -1;
	} 
  	
	memcpy(pNetIf->hwaddr, ifr.ifr_hwaddr.sa_data, ETH_ALEN);

	//Take MAC address convert to string
	printf("The MAC address is %s\n", hwaddr_to_str(pNetIf->hwaddr));
	
	return 0;	 
}

char *hwaddr_to_str(unsigned char *ha)
{
	int i;
	static char macstr_buf[HWADDR_STR_LEN] = {'\0', };

	memset(macstr_buf, 0x00, HWADDR_STR_LEN);

	for ( i = 0 ; i < ETH_ALEN ; i++)
	{
		hexNumToStr(ha[i],&macstr_buf[i*3]);
		if ( i < 5 )
		{
			macstr_buf[(i+1)*3-1] = ':';
		}
	}
	return macstr_buf;
}

void hexNumToStr(unsigned int number ,char *str)
{
	char * AsciiNum={"0123456789ABCDEF"};
	
	str[0]=AsciiNum[(number>> 4)&0xf];
	str[1]=AsciiNum[number&0xf];
}

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章