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 <sameo@linux.intel.com>
This commit is contained in:
Samuel Ortiz 2019-05-10 07:08:37 +02:00
parent 5934f30fde
commit 576a28ae5e
4 changed files with 16 additions and 0 deletions

1
Cargo.lock generated
View File

@ -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)",
]

View File

@ -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" }

View File

@ -11,6 +11,7 @@
#[macro_use]
extern crate lazy_static;
extern crate libc;
extern crate rand;
extern crate serde;
extern crate net_gen;

View File

@ -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 {