linux C 网络编程或者路由开发等,需要不同的mac字符串的要求。这些代码很简单,为大家提供一些即粘即用吧 节省一点无聊的开发。哈哈
//type
//0--upper,no :,1--lower,with :,2----lower,no:,3-----upper with :
int get_devmac(int type,char *ifname,char *buffer)
{
struct ifreq ifr;
int ret = -1;
int sockfd;
if( (sockfd = socket(AF_INET, SOCK_DGRAM, 0))<0 )
{
printf("[Socket error] Socket opening error!\n");
return -10;
}
ifr.ifr_addr.sa_family = AF_INET;
strcpy(ifr.ifr_name,ifname);
if (ioctl (sockfd, SIOCGIFHWADDR, &ifr) < 0)
{
ret = errno;
printf("[MAC error]%s\n",strerror(errno));
}else
{
unsigned char *mac = (unsigned char *) ifr.ifr_hwaddr.sa_data;
if(type ==0){
sprintf(buffer,"%.2X%.2X%.2X%.2X%.2X%.2X",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
ret = 0;
}else if(type == 1){
sprintf(buffer,"%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
ret = 0;
}
else if(type == 2){
sprintf(buffer,"%.2x%.2x%.2x%.2x%.2x%.2x",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
ret = 0;
}
else if(type == 3){
sprintf(buffer,"%.2X:%.2X:%.2X:%.2X:%.2X:%.2X",mac[0],mac[1],mac[2],mac[3],mac[4],mac[5]);
ret = 0;
}
}
close(sockfd);
return ret;
}
//0--upper,no :,1--lower,with :,2----lower,no:
//buffer is upper,no:
int get_upper_nocolon_mac(char *devmac,char *buffer){
int i = 0,num=0,len = strlen(devmac);
for(i=0;i<len;i++){
if(devmac[i] != ':'){
buffer[num] = toupper(devmac[i]);
num++;
}
}
return 0;
}
int get_lower_nocolon_mac(char *devmac,char *buffer){
int i = 0,num=0,len = strlen(devmac);
for(i=0;i<len;i++){
if(devmac[i] != ':'){
buffer[num] = tolower(devmac[i]);
num++;
}
}
return 0;
}
int get_lower_colon_mac(char *devmac,char *buffer){
int i = 0,num=1,len = strlen(devmac);
for(i=0;i<len;i++){
if(len == 17){
buffer[i] = tolower(devmac[i]);
}
else{
if(num != 1 && num %3 == 0){
buffer[num-1] = ':';
if(i != 0)
i--;
}else{
buffer[num-1] = tolower(devmac[i]);
//num++;
}
num++;
}
}
return 0;
}