Friday, April 1, 2011

Generating a Type 1 UUID with Ethernet Address

Now that we know how to get get our hardware or MAC address, we can use it to generate a type 1 UUID. The reason that you would add the ethernet address to the UUID would be to guarantee uniqueness when you're generating UUIDs on multiple machines. You want to guarantee uniqueness across those machines.

The drawback is that the address becomes part of the UUID which could be a security concern. The other possibility is to generate a fake address for each machine which could also guarantee uniqueness while getting around the possible security issue.

Here's the code to do it. Yes, this is using CDI to inject the UUID. You can replicate this using any DI framework or by simply using the class directly.

public class UuidService implements Serializable {
    private UUIDGenerator uuidGen = null;
    private EthernetAddress ethernet = null;

    * Set up the uuid generator
   private void init() {
        uuidGen = UUIDGenerator.getInstance();
        try {
            Enumeration<NetworkInterface> ns = NetworkInterface.getNetworkInterfaces();
            while (ns.hasMoreElements()) {           
                NetworkInterface n = ns.nextElement();
                if (n.isUp() && !n.isLoopback()) {
                    // Grab the first external network interface and get the hardware address for UUID
                    byte[] byteAddress = n.getHardwareAddress();
                    ethernet = new EthernetAddress(byteAddress);
        } catch (SocketException ex) {
            Logger.getLogger(UuidService.class.getName()).log(Level.SEVERE, null, ex);
     * UUID
     * @return
    public String nextId() {
        return uuidGen.generateTimeBasedUUID(ethernet).toString();

Here is the injection part.

    @Inject UuidService service;
    User u = new User(service.nextId());

1 comment:

  1. Its really great post. Thanks a lot for sharing such an useful information with us.
    PEO Networking