From 43383b31e18921a4b740dbe2d66c9fc1f86474ca Mon Sep 17 00:00:00 2001 From: James Logan Date: Mon, 5 Feb 2024 18:18:51 -0500 Subject: [PATCH] just initialize with an address and add a note that the function for setting the ip address mutates an entry --- examples/dhcp_client.rs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/examples/dhcp_client.rs b/examples/dhcp_client.rs index bb6ec556a..a2e2f6dc3 100644 --- a/examples/dhcp_client.rs +++ b/examples/dhcp_client.rs @@ -38,6 +38,13 @@ fn main() { config.random_seed = rand::random(); let mut iface = Interface::new(config, &mut device, Instant::now()); + // Initialize with an address so that there is something to mutate later. + // This also allows sockets made before a real address is negotiated + // via DHCP to update properly afterward. + iface.update_ip_addrs(|addrs| { + addrs.push(IpCidr::Ipv4(Ipv4Cidr::new(Ipv4Address::UNSPECIFIED, 0))).unwrap(); + }); + // Create sockets let mut dhcp_socket = dhcpv4::Socket::new(); @@ -77,7 +84,6 @@ fn main() { } Some(dhcpv4::Event::Deconfigured) => { debug!("DHCP lost config!"); - iface.update_ip_addrs(|addrs| addrs.clear()); set_ipv4_addr(&mut iface, Ipv4Cidr::new(Ipv4Address::UNSPECIFIED, 0)); iface.routes_mut().remove_default_ipv4_route(); } @@ -87,8 +93,10 @@ fn main() { } } +/// Mutate the first IP address to match the one supplied fn set_ipv4_addr(iface: &mut Interface, cidr: Ipv4Cidr) { iface.update_ip_addrs(|addrs| { - addrs.push(IpCidr::Ipv4(cidr)).unwrap(); + let dest = addrs.iter_mut().next().unwrap(); + *dest = IpCidr::Ipv4(cidr); }); }