]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org/argeo/api/uuid/MacAddressUuidFactory.java
Prepare next development cycle
[lgpl/argeo-commons.git] / org / argeo / api / uuid / MacAddressUuidFactory.java
1 package org.argeo.api.uuid;
2
3 import java.net.InetAddress;
4 import java.net.NetworkInterface;
5 import java.net.SocketException;
6 import java.net.UnknownHostException;
7 import java.util.Enumeration;
8 import java.util.UUID;
9
10 /**
11 * An {@link UUID} factory whose node id (for time based UUIDs) is the hardware
12 * MAC address as specified in RFC4122.
13 *
14 * @see https://datatracker.ietf.org/doc/html/rfc4122.html#section-4.1.6
15 */
16 public class MacAddressUuidFactory extends ConcurrentUuidFactory {
17 public final static UuidFactory DEFAULT = new MacAddressUuidFactory();
18
19 public MacAddressUuidFactory() {
20 this(0, localHardwareAddressAsNodeId());
21 }
22
23 public MacAddressUuidFactory(long initialClockRange) {
24 this(initialClockRange, localHardwareAddressAsNodeId());
25 }
26
27 public MacAddressUuidFactory(byte[] hardwareAddress) {
28 this(0, hardwareAddress);
29 }
30
31 public MacAddressUuidFactory(long initialClockRange, byte[] hardwareAddress) {
32 super(initialClockRange, hardwareAddress);
33 }
34
35 private static byte[] localHardwareAddressAsNodeId() {
36 InetAddress localHost;
37 try {
38 localHost = InetAddress.getLocalHost();
39 NetworkInterface nic = NetworkInterface.getByInetAddress(localHost);
40 if (nic != null)
41 return hardwareAddressToNodeId(nic);
42 Enumeration<NetworkInterface> netInterfaces = null;
43 try {
44 netInterfaces = NetworkInterface.getNetworkInterfaces();
45 } catch (SocketException e) {
46 throw new IllegalStateException(e);
47 }
48 if (netInterfaces == null || !netInterfaces.hasMoreElements())
49 throw new IllegalStateException("No interfaces");
50 return hardwareAddressToNodeId(netInterfaces.nextElement());
51 } catch (UnknownHostException | SocketException e) {
52 throw new IllegalStateException(e);
53 }
54
55 }
56
57 public static byte[] hardwareAddressToNodeId(NetworkInterface nic) {
58 try {
59 byte[] hardwareAddress = nic.getHardwareAddress();
60 final int length = 6;
61 byte[] arr = new byte[length];
62 for (int i = 0; i < length; i++) {
63 arr[i] = hardwareAddress[length - 1 - i];
64 }
65 return arr;
66 } catch (SocketException e) {
67 throw new IllegalStateException("Cannot retrieve hardware address from NIC", e);
68 }
69 }
70
71 }