Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a random mac address generator generate just unicast macs

This is my simple mac address generator:

private String randomMACAddress(){
    Random rand = new Random();
    byte[] macAddr = new byte[6];
    rand.nextBytes(macAddr);

    StringBuilder sb = new StringBuilder(18);
    for(byte b : macAddr){
        if(sb.length() > 0){
            sb.append(":");
        }else{ //first byte, we need to set some options
            b = (byte)(b | (byte)(0x01 << 6)); //locally adminstrated
            b = (byte)(b | (byte)(0x00 << 7)); //unicast

        }
        sb.append(String.format("%02x", b));
    }


    return sb.toString();
}

Note how I set and unset bits to make so it generates unicast macs. However it doesn't work and my automated program which accepts mac addresses returns me an error because "this mac address is multicast".

What am I doing wrong?

like image 947
Phate Avatar asked Jun 17 '14 10:06

Phate


1 Answers

Solved...I just made

private String randomMACAddress(){
    Random rand = new Random();
    byte[] macAddr = new byte[6];
    rand.nextBytes(macAddr);

    macAddr[0] = (byte)(macAddr[0] & (byte)254);  //zeroing last 2 bytes to make it unicast and locally adminstrated

    StringBuilder sb = new StringBuilder(18);
    for(byte b : macAddr){

        if(sb.length() > 0)
            sb.append(":");

        sb.append(String.format("%02x", b));
    }


    return sb.toString();
}
like image 137
Phate Avatar answered Nov 02 '22 11:11

Phate