怎樣經由過程C說話主動生成MAC地址。本站提示廣大學習愛好者:(怎樣經由過程C說話主動生成MAC地址)文章只能為提供參考,不一定能成為您想要的結果。以下是怎樣經由過程C說話主動生成MAC地址正文
比來在做虛擬機項目時,須要給創立的每個虛擬機主動生成一個MAC地址,因為MAC地址為48位,並且格局是以:離隔的,所以上面我寫了一個c法式,來主動生成MAC地址。
// MAC.c
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<unistd.h>
#define RANDOM(x) (rand()%x)
#define MAC_ADDR_LENGTH 12
#define FMT_MAC_ADDR_LEN (MAC_ADDR_LENGTH+5)
unsigned char HEXCHAR[16]={'0','1','2','3','4','5','6','7','8','9','A','B','C',
'D','E','F'};
unsigned char genMACAddr[MAC_ADDR_LENGTH];
unsigned char fmtMACAddr[FMT_MAC_ADDR_LEN]={'0','0','-','0','0','-','0','0','-',
'0','0','-','0','0','-','0','0'};
void formatMACAddr()
{
unsigned short i=0;
unsigned short n=0;
for(i=0;i<MAC_ADDR_LENGTH;i++,n++)
{
if(fmtMACAddr[n]!='-')
{
fmtMACAddr[n]=genMACAddr[i];
}
else
{
n++;
fmtMACAddr[n]=genMACAddr[i];
}
}
}
void main()
{
unsigned short i=0;
unsigned short n=0;
srand(getpid());
for(int i=0;i<MAC_ADDR_LENGTH;i++)
{
n=RANDOM(16);
genMACAddr[i]=HEXCHAR[n];
}
formatMACAddr();
printf("%s",fmtMACAddr);
}