Make a random mac address generator generate just unicast macs

Phate picture Phate · Jun 17, 2014 · Viewed 9.9k times · Source

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?

Answer

Phate picture Phate · Jun 17, 2014

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();
}