dhcp_client.rs 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #![allow(clippy::option_map_unit_fn)]
  2. mod utils;
  3. use log::*;
  4. use std::os::unix::io::AsRawFd;
  5. use smoltcp::iface::{Interface, InterfaceBuilder, NeighborCache, SocketSet};
  6. use smoltcp::socket::dhcpv4;
  7. use smoltcp::time::Instant;
  8. use smoltcp::wire::{EthernetAddress, IpCidr, Ipv4Address, Ipv4Cidr};
  9. use smoltcp::{
  10. phy::{wait as phy_wait, Device, Medium},
  11. time::Duration,
  12. };
  13. fn main() {
  14. #[cfg(feature = "log")]
  15. utils::setup_logging("");
  16. let (mut opts, mut free) = utils::create_options();
  17. utils::add_tuntap_options(&mut opts, &mut free);
  18. utils::add_middleware_options(&mut opts, &mut free);
  19. let mut matches = utils::parse_options(&opts, free);
  20. let device = utils::parse_tuntap_options(&mut matches);
  21. let fd = device.as_raw_fd();
  22. let mut device =
  23. utils::parse_middleware_options(&mut matches, device, /*loopback=*/ false);
  24. let neighbor_cache = NeighborCache::new();
  25. let ethernet_addr = EthernetAddress([0x02, 0x00, 0x00, 0x00, 0x00, 0x01]);
  26. let mut ip_addrs = heapless::Vec::<IpCidr, 5>::new();
  27. ip_addrs
  28. .push(IpCidr::new(Ipv4Address::UNSPECIFIED.into(), 0))
  29. .unwrap();
  30. let medium = device.capabilities().medium;
  31. let mut builder = InterfaceBuilder::new().ip_addrs(ip_addrs);
  32. if medium == Medium::Ethernet {
  33. builder = builder
  34. .hardware_addr(ethernet_addr.into())
  35. .neighbor_cache(neighbor_cache);
  36. }
  37. let mut iface = builder.finalize(&mut device);
  38. let mut dhcp_socket = dhcpv4::Socket::new();
  39. // Set a ridiculously short max lease time to show DHCP renews work properly.
  40. // This will cause the DHCP client to start renewing after 5 seconds, and give up the
  41. // lease after 10 seconds if renew hasn't succeeded.
  42. // IMPORTANT: This should be removed in production.
  43. dhcp_socket.set_max_lease_duration(Some(Duration::from_secs(10)));
  44. let mut sockets = SocketSet::new(vec![]);
  45. let dhcp_handle = sockets.add(dhcp_socket);
  46. loop {
  47. let timestamp = Instant::now();
  48. iface.poll(timestamp, &mut device, &mut sockets);
  49. let event = sockets.get_mut::<dhcpv4::Socket>(dhcp_handle).poll();
  50. match event {
  51. None => {}
  52. Some(dhcpv4::Event::Configured(config)) => {
  53. debug!("DHCP config acquired!");
  54. debug!("IP address: {}", config.address);
  55. set_ipv4_addr(&mut iface, config.address);
  56. if let Some(router) = config.router {
  57. debug!("Default gateway: {}", router);
  58. iface.routes_mut().add_default_ipv4_route(router).unwrap();
  59. } else {
  60. debug!("Default gateway: None");
  61. iface.routes_mut().remove_default_ipv4_route();
  62. }
  63. for (i, s) in config.dns_servers.iter().enumerate() {
  64. debug!("DNS server {}: {}", i, s);
  65. }
  66. }
  67. Some(dhcpv4::Event::Deconfigured) => {
  68. debug!("DHCP lost config!");
  69. set_ipv4_addr(&mut iface, Ipv4Cidr::new(Ipv4Address::UNSPECIFIED, 0));
  70. iface.routes_mut().remove_default_ipv4_route();
  71. }
  72. }
  73. phy_wait(fd, iface.poll_delay(timestamp, &sockets)).expect("wait error");
  74. }
  75. }
  76. fn set_ipv4_addr(iface: &mut Interface<'_>, cidr: Ipv4Cidr) {
  77. iface.update_ip_addrs(|addrs| {
  78. let dest = addrs.iter_mut().next().unwrap();
  79. *dest = IpCidr::Ipv4(cidr);
  80. });
  81. }