dhcp_client.rs 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #![allow(clippy::option_map_unit_fn)]
  2. mod utils;
  3. use log::*;
  4. use std::os::unix::io::AsRawFd;
  5. use smoltcp::iface::{Config, Interface, 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. // Create interface
  25. let mut config = Config::new();
  26. config.random_seed = rand::random();
  27. if device.capabilities().medium == Medium::Ethernet {
  28. config.hardware_addr = Some(EthernetAddress([0x02, 0x00, 0x00, 0x00, 0x00, 0x01]).into());
  29. }
  30. let mut iface = Interface::new(config, &mut device);
  31. // Create sockets
  32. let mut dhcp_socket = dhcpv4::Socket::new();
  33. // Set a ridiculously short max lease time to show DHCP renews work properly.
  34. // This will cause the DHCP client to start renewing after 5 seconds, and give up the
  35. // lease after 10 seconds if renew hasn't succeeded.
  36. // IMPORTANT: This should be removed in production.
  37. dhcp_socket.set_max_lease_duration(Some(Duration::from_secs(10)));
  38. let mut sockets = SocketSet::new(vec![]);
  39. let dhcp_handle = sockets.add(dhcp_socket);
  40. loop {
  41. let timestamp = Instant::now();
  42. iface.poll(timestamp, &mut device, &mut sockets);
  43. let event = sockets.get_mut::<dhcpv4::Socket>(dhcp_handle).poll();
  44. match event {
  45. None => {}
  46. Some(dhcpv4::Event::Configured(config)) => {
  47. debug!("DHCP config acquired!");
  48. debug!("IP address: {}", config.address);
  49. set_ipv4_addr(&mut iface, config.address);
  50. if let Some(router) = config.router {
  51. debug!("Default gateway: {}", router);
  52. iface.routes_mut().add_default_ipv4_route(router).unwrap();
  53. } else {
  54. debug!("Default gateway: None");
  55. iface.routes_mut().remove_default_ipv4_route();
  56. }
  57. for (i, s) in config.dns_servers.iter().enumerate() {
  58. debug!("DNS server {}: {}", i, s);
  59. }
  60. }
  61. Some(dhcpv4::Event::Deconfigured) => {
  62. debug!("DHCP lost config!");
  63. set_ipv4_addr(&mut iface, Ipv4Cidr::new(Ipv4Address::UNSPECIFIED, 0));
  64. iface.routes_mut().remove_default_ipv4_route();
  65. }
  66. }
  67. phy_wait(fd, iface.poll_delay(timestamp, &sockets)).expect("wait error");
  68. }
  69. }
  70. fn set_ipv4_addr(iface: &mut Interface, cidr: Ipv4Cidr) {
  71. iface.update_ip_addrs(|addrs| {
  72. let dest = addrs.iter_mut().next().unwrap();
  73. *dest = IpCidr::Ipv4(cidr);
  74. });
  75. }