linux生成随机MAC地址

我们前3字节固定,只随机生成后3字节,主要实现思路是读取kernel产生的uuid作为随机数的种子,这样能保证所有出厂机器随机数种子不同,从而尽可能的避免产生重复的MAC地址。随机产生MAC地址并不是可取的办法,不能保证没有重复的,最好的办法还是自己做一个设置MAC地址的工具,和数据库中的地址比对,保证唯一性。    

   char mac[20]="";
    ret=getMac("mac=", mac, sizeof(mac)-1);
    if(strncmp(mac,"00:90:C3:00:00:01",strlen("00:90:C3:00:00:01"))==0)
    {
        unsigned long sed=time(0);
        int fd=open("/proc/sys/kernel/random/uuid",O_RDONLY);
        if(fd>0) 
        {
            unsigned char tmp[40];
            memset(tmp,'\0',sizeof(tmp));
            read(fd,tmp,sizeof(tmp));
            for(int i=0;i                 sed+=(tmp[i]&0xff)*pow(10,i%8);
            }
            close(fd);
        }

        printf("\nsed=%u\n",sed);
        srandom(sed);

        unsigned char rnd[3];
        for(int i=0;i<3;i++)
        {
            unsigned long tmp;
            unsigned char loop=0;
            do{
                tmp=random();
                if(++loop>1000) break;
            }while(tmp>0xff);

            if(tmp>0xff){
                tmp=(tmp-(tmp/255)*255)-1;
                printf("\ntmp=%u\n",tmp);
            }
            rnd[i]=tmp&0xff;
        }
        sprintf(mac,"00:90:C3:%02X:%02X:%02X",rnd[0],rnd[1],rnd[2]);
        ret=setMac(mac);
        system("reboot");
    }

你可能感兴趣的:(c,linux)