uuid_helper/lib.rs
1use std::sync::LazyLock;
2pub use uuid;
3use uuid::Uuid;
4
5static MAC: LazyLock<[u8; 6]> = LazyLock::new(get_mac_address_once);
6
7/// Obtain the mac address of the first non-loopback interface on the system.
8/// If there are no candidate interfaces, fall back to the `gethostid()` function,
9/// which will attempt to load a host id from a file on the filesystem, or if that
10/// fails, resolve the hostname of the node to its IPv4 address using a reverse DNS
11/// lookup, and then derive some 32-bit number from that address through unspecified
12/// means.
13fn get_mac_address_once() -> [u8; 6] {
14 match mac_address::get_mac_address() {
15 Ok(Some(addr)) => addr.bytes(),
16 _ => {
17 // Fall back to gethostid, which is not great, but
18 // likely better than just random numbers
19 let host_id = unsafe { libc::gethostid() }.to_le_bytes();
20 let mac: [u8; 6] = [
21 host_id[0], host_id[1], host_id[2], host_id[3], host_id[4], host_id[5],
22 ];
23 mac
24 }
25 }
26}
27
28pub fn get_mac_address() -> &'static [u8; 6] {
29 &MAC
30}
31
32pub fn now_v1() -> uuid::Uuid {
33 Uuid::now_v1(&MAC)
34}
35
36pub fn new_v1(ts: uuid::timestamp::Timestamp) -> uuid::Uuid {
37 Uuid::new_v1(ts, &MAC)
38}