8000 dhcpd: allow specifying the interface name as a command-line arg · Andy-Python-Programmer/dhcpd@ac3154e · GitHub
[go: up one dir, main page]

Skip to content

Commit ac3154e

Browse files
no92Andy-Python-Programmer
authored andcommitted
dhcpd: allow specifying the interface name as a command-line arg
1 parent f226b6b commit ac3154e

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

src/main.rs

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -370,13 +370,26 @@ pub fn cvt(t: i32) -> io::Result<i32> {
370370
}
371371
}
372372

373+
fn get_nicname<'a>() -> &'a str {
374+
static CACHED: Once<String> = Once::new();
375+
376+
CACHED.call_once(|| {
377+
let nic_name = std::env::args().nth(1).unwrap_or(DEFAULT_NIC.to_string());
378+
379+
get_index(&nic_name)
380+
.unwrap_or_else(|nic_name| panic!("[ DHCPD ] (EE) invalid NIC name {}", nic_name));
381+
382+
nic_name
383+
})
384+
}
385+
373386
fn get_macaddress<'a>() -> &'a [u8; 6] {
374387
static CACHED: Once<[u8; 6]> = Once::new();
375388
CACHED
376389
.try_call_once(|| unsafe {
377390
let fd = cvt(libc::socket(libc::AF_INET, libc::SOCK_DGRAM, 0))?;
378391

379-
let macaddr = IfReq::new(DEFAULT_NIC);
392+
let macaddr = IfReq::new(get_nicname());
380393
cvt(libc::ioctl(fd, libc::SIOCGIFHWADDR, &macaddr))?;
381394

382395
Ok::<[u8; 6], io::Error>(macaddr.macaddr())
@@ -469,6 +482,14 @@ fn configure(interface: &str, ip: Ipv4Addr, subnet_mask: Ipv4Addr) -> io::Result
469482

470483
const DEFAULT_NIC: &str = "eth0"; // FIXME: retrieve the default NIC from the kernel
471484

485+
fn get_index(nic: &str) -> io::Result<libc::c_uint> {
486+
let ifname = std::ffi::CString::new(nic)?;
487+
match unsafe { libc::if_nametoindex(ifname.as_ptr()) } {
488+
0 => Err(io::Error::last_os_error()),
489+
index => Ok(index),
490+
}
491+
}
492+
472493
pub fn main() -> Result<(), Box<dyn Error>> {
473494
let socket = UdpSocket::bind(("0.0.0.0", DHCP_CLIENT_PORT))?;
474495

@@ -520,7 +541,7 @@ pub fn main() -> Result<(), Box<dyn Error>> {
520541
let subnet_mask = subnet_mask.unwrap();
521542
let dns = dns.unwrap();
522543

523-
configure(DEFAULT_NIC, ack.your_ip, subnet_mask)?;
544+
configure(get_nicname(), ack.your_ip, subnet_mask)?;
524545

525546
println!("[ DHCPD ] (!!) Configured:");
526547
println!("[ DHCPD ] (!!) IP: {}", ack.your_ip);

0 commit comments

Comments
 (0)
0