Search code examples
javanetworkingmac-address

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?


Solution

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