@@ -370,13 +370,26 @@ pub fn cvt(t: i32) -> io::Result<i32> {
370
370
}
371
371
}
372
372
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
+
373
386
fn get_macaddress < ' a > ( ) -> & ' a [ u8 ; 6 ] {
374
387
static CACHED : Once < [ u8 ; 6 ] > = Once :: new ( ) ;
375
388
CACHED
376
389
. try_call_once ( || unsafe {
377
390
let fd = cvt ( libc:: socket ( libc:: AF_INET , libc:: SOCK_DGRAM , 0 ) ) ?;
378
391
379
- let macaddr = IfReq :: new ( DEFAULT_NIC ) ;
392
+ let macaddr = IfReq :: new ( get_nicname ( ) ) ;
380
393
cvt ( libc:: ioctl ( fd, libc:: SIOCGIFHWADDR , & macaddr) ) ?;
381
394
382
395
Ok :: < [ u8 ; 6 ] , io:: Error > ( macaddr. macaddr ( ) )
@@ -469,6 +482,14 @@ fn configure(interface: &str, ip: Ipv4Addr, subnet_mask: Ipv4Addr) -> io::Result
469
482
470
483
const DEFAULT_NIC : & str = "eth0" ; // FIXME: retrieve the default NIC from the kernel
471
484
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
+
472
493
pub fn main ( ) -> Result < ( ) , Box < dyn Error > > {
473
494
let socket = UdpSocket :: bind ( ( "0.0.0.0" , DHCP_CLIENT_PORT ) ) ?;
474
495
@@ -520,7 +541,7 @@ pub fn main() -> Result<(), Box<dyn Error>> {
520
541
let subnet_mask = subnet_mask. unwrap ( ) ;
521
542
let dns = dns. unwrap ( ) ;
522
543
523
- configure ( DEFAULT_NIC , ack. your_ip , subnet_mask) ?;
544
+ configure ( get_nicname ( ) , ack. your_ip , subnet_mask) ?;
524
545
525
546
println ! ( "[ DHCPD ] (!!) Configured:" ) ;
526
547
println ! ( "[ DHCPD ] (!!) IP: {}" , ack. your_ip) ;
0 commit comments