]>
git.argeo.org Git - lgpl/argeo-commons.git/blob - uuid/MacAddressUuidFactory.java
1 package org
.argeo
.api
.uuid
;
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
;
11 * An {@link UUID} factory whose node id (for time based UUIDs) is the hardware
12 * MAC address as specified in RFC4122.
14 * @see "https://datatracker.ietf.org/doc/html/rfc4122.html#section-4.1.6"
16 public class MacAddressUuidFactory
extends ConcurrentUuidFactory
{
17 public MacAddressUuidFactory() {
18 this(0, localHardwareAddressAsNodeId());
21 public MacAddressUuidFactory(long initialClockRange
) {
22 this(initialClockRange
, localHardwareAddressAsNodeId());
25 public MacAddressUuidFactory(byte[] hardwareAddress
) {
26 this(0, hardwareAddress
);
29 public MacAddressUuidFactory(long initialClockRange
, byte[] hardwareAddress
) {
30 super(initialClockRange
, hardwareAddress
);
33 private static byte[] localHardwareAddressAsNodeId() {
34 InetAddress localHost
;
36 localHost
= InetAddress
.getLocalHost();
37 NetworkInterface nic
= NetworkInterface
.getByInetAddress(localHost
);
39 return hardwareAddressToNodeId(nic
);
40 Enumeration
<NetworkInterface
> netInterfaces
= null;
42 netInterfaces
= NetworkInterface
.getNetworkInterfaces();
43 } catch (SocketException e
) {
44 throw new IllegalStateException(e
);
46 if (netInterfaces
== null || !netInterfaces
.hasMoreElements())
47 throw new IllegalStateException("No interfaces");
48 return hardwareAddressToNodeId(netInterfaces
.nextElement());
49 } catch (UnknownHostException
| SocketException e
) {
50 throw new IllegalStateException(e
);
55 public static byte[] hardwareAddressToNodeId(NetworkInterface nic
) {
57 byte[] hardwareAddress
= nic
.getHardwareAddress();
59 byte[] arr
= new byte[length
];
60 for (int i
= 0; i
< length
; i
++) {
61 arr
[i
] = hardwareAddress
[length
- 1 - i
];
64 } catch (SocketException e
) {
65 throw new IllegalStateException("Cannot retrieve hardware address from NIC", e
);