Recently in the virtual machine project, you need to create a virtual machine automatically generate a MAC address, because the MAC address is 48 bits, and the format is: separated, so I wrote a C program, to automatically generate MAC address.
Copy Code code as follows:
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);
}