From 576a28ae5e2fc3c66743285b660c3d1c43700354 Mon Sep 17 00:00:00 2001 From: Samuel Ortiz Date: Fri, 10 May 2019 07:08:37 +0200 Subject: [PATCH] net_util: Add helper for generating a random local MAC We must ensure our MAC addresses do not conflict with a global one. Signed-off-by: Samuel Ortiz --- Cargo.lock | 1 + net_util/Cargo.toml | 1 + net_util/src/lib.rs | 1 + net_util/src/mac.rs | 13 +++++++++++++ 4 files changed, 16 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 47f6a64cd..1a4daf607 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -157,6 +157,7 @@ version = "0.1.0" dependencies = [ "libc 0.2.54 (registry+https://github.com/rust-lang/crates.io-index)", "net_gen 0.1.0", + "rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.91 (registry+https://github.com/rust-lang/crates.io-index)", "vmm-sys-util 0.1.0 (git+https://github.com/liujing2/vmm-sys-util)", ] diff --git a/net_util/Cargo.toml b/net_util/Cargo.toml index 5c56bdf7c..74b646650 100644 --- a/net_util/Cargo.toml +++ b/net_util/Cargo.toml @@ -5,6 +5,7 @@ authors = ["The Chromium OS Authors"] [dependencies] libc = ">=0.2.39" +rand = ">=0.6.5" serde = ">=1.0.27" net_gen = { path = "../net_gen" } diff --git a/net_util/src/lib.rs b/net_util/src/lib.rs index 8ebd0b2e2..4c11592ac 100644 --- a/net_util/src/lib.rs +++ b/net_util/src/lib.rs @@ -11,6 +11,7 @@ #[macro_use] extern crate lazy_static; extern crate libc; +extern crate rand; extern crate serde; extern crate net_gen; diff --git a/net_util/src/mac.rs b/net_util/src/mac.rs index 7fa29fad0..cb6cdb805 100644 --- a/net_util/src/mac.rs +++ b/net_util/src/mac.rs @@ -5,6 +5,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. +use rand::Rng; use std::result::Result; use serde::de::{Deserialize, Deserializer, Error}; @@ -72,6 +73,18 @@ impl MacAddr { b[0], b[1], b[2], b[3], b[4], b[5] ) } + + pub fn local_random() -> MacAddr { + // Generate a fully random MAC + let mut random_bytes = rand::thread_rng().gen::<[u8; MAC_ADDR_LEN]>(); + + // Set the first byte to make the OUI a locally administered OUI + random_bytes[0] = 0x2e; + + MacAddr { + bytes: random_bytes, + } + } } impl Serialize for MacAddr {