ping.rs 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. #[macro_use]
  2. extern crate log;
  3. extern crate env_logger;
  4. extern crate getopts;
  5. extern crate smoltcp;
  6. extern crate byteorder;
  7. mod utils;
  8. use std::str::FromStr;
  9. use std::collections::BTreeMap;
  10. use std::time::Instant;
  11. use std::os::unix::io::AsRawFd;
  12. use smoltcp::phy::Device;
  13. use smoltcp::phy::wait as phy_wait;
  14. use smoltcp::wire::{EthernetAddress, IpAddress, IpCidr,
  15. Ipv4Address, Icmpv4Repr, Icmpv4Packet};
  16. use smoltcp::iface::{NeighborCache, EthernetInterfaceBuilder};
  17. use smoltcp::socket::{SocketSet, IcmpSocket, IcmpSocketBuffer, IcmpPacketBuffer, IcmpEndpoint};
  18. use std::collections::HashMap;
  19. use byteorder::{ByteOrder, NetworkEndian};
  20. fn main() {
  21. utils::setup_logging("warn");
  22. let (mut opts, mut free) = utils::create_options();
  23. utils::add_tap_options(&mut opts, &mut free);
  24. utils::add_middleware_options(&mut opts, &mut free);
  25. opts.optopt("c", "count", "Amount of echo request packets to send (default: 4)", "COUNT");
  26. opts.optopt("i", "interval",
  27. "Interval between successive packets sent (seconds) (default: 1)", "INTERVAL");
  28. opts.optopt("", "timeout",
  29. "Maximum wait duration for an echo response packet (seconds) (default: 5)",
  30. "TIMEOUT");
  31. free.push("ADDRESS");
  32. let mut matches = utils::parse_options(&opts, free);
  33. let device = utils::parse_tap_options(&mut matches);
  34. let fd = device.as_raw_fd();
  35. let device = utils::parse_middleware_options(&mut matches, device, /*loopback=*/false);
  36. let device_caps = device.capabilities();
  37. let address = Ipv4Address::from_str(&matches.free[0]).expect("invalid address format");
  38. let count = matches.opt_str("count").map(|s| usize::from_str(&s).unwrap()).unwrap_or(4);
  39. let interval = matches.opt_str("interval").map(|s| u64::from_str(&s).unwrap()).unwrap_or(1);
  40. let timeout = matches.opt_str("timeout").map(|s| u64::from_str(&s).unwrap()).unwrap_or(5);
  41. let startup_time = Instant::now();
  42. let neighbor_cache = NeighborCache::new(BTreeMap::new());
  43. let remote_addr = address;
  44. let local_addr = Ipv4Address::new(192, 168, 69, 1);
  45. let icmp_rx_buffer = IcmpSocketBuffer::new(vec![IcmpPacketBuffer::new(vec![0; 256])]);
  46. let icmp_tx_buffer = IcmpSocketBuffer::new(vec![IcmpPacketBuffer::new(vec![0; 256])]);
  47. let icmp_socket = IcmpSocket::new(icmp_rx_buffer, icmp_tx_buffer);
  48. let ethernet_addr = EthernetAddress([0x02, 0x00, 0x00, 0x00, 0x00, 0x02]);
  49. let ip_addr = IpCidr::new(IpAddress::from(local_addr), 24);
  50. let default_v4_gw = Ipv4Address::new(192, 168, 69, 100);
  51. let mut iface = EthernetInterfaceBuilder::new(device)
  52. .ethernet_addr(ethernet_addr)
  53. .ip_addrs([ip_addr])
  54. .ipv4_gateway(default_v4_gw)
  55. .neighbor_cache(neighbor_cache)
  56. .finalize();
  57. let mut sockets = SocketSet::new(vec![]);
  58. let icmp_handle = sockets.add(icmp_socket);
  59. let mut send_at = 0;
  60. let mut seq_no = 0;
  61. let mut received = 0;
  62. let mut echo_payload = [0xffu8; 40];
  63. let mut waiting_queue = HashMap::new();
  64. let ident = 0x22b;
  65. let endpoint = IpAddress::Ipv4(remote_addr);
  66. loop {
  67. {
  68. let mut socket = sockets.get::<IcmpSocket>(icmp_handle);
  69. if !socket.is_open() {
  70. socket.bind(IcmpEndpoint::Ident(ident)).unwrap()
  71. }
  72. let timestamp = Instant::now().duration_since(startup_time);
  73. let timestamp_us = (timestamp.as_secs() * 1000000) +
  74. (timestamp.subsec_nanos() / 1000) as u64;
  75. if socket.can_send() && seq_no < count as u16 &&
  76. send_at <= utils::millis_since(startup_time) {
  77. NetworkEndian::write_u64(&mut echo_payload, timestamp_us);
  78. let icmp_repr = Icmpv4Repr::EchoRequest {
  79. ident: ident,
  80. seq_no,
  81. data: &echo_payload,
  82. };
  83. let icmp_payload = socket
  84. .send(icmp_repr.buffer_len(), endpoint)
  85. .unwrap();
  86. let mut icmp_packet = Icmpv4Packet::new(icmp_payload);
  87. icmp_repr.emit(&mut icmp_packet, &device_caps.checksum);
  88. waiting_queue.insert(seq_no, timestamp);
  89. seq_no += 1;
  90. send_at += interval * 1000;
  91. }
  92. if socket.can_recv() {
  93. let (payload, _) = socket.recv().unwrap();
  94. let icmp_packet = Icmpv4Packet::new(&payload);
  95. let icmp_repr = Icmpv4Repr::parse(&icmp_packet, &device_caps.checksum).unwrap();
  96. if let Icmpv4Repr::EchoReply { seq_no, data, .. } = icmp_repr {
  97. if let Some(_) = waiting_queue.get(&seq_no) {
  98. let packet_timestamp_us = NetworkEndian::read_u64(data);
  99. println!("{} bytes from {}: icmp_seq={}, time={:.3}ms",
  100. data.len(), remote_addr, seq_no,
  101. (timestamp_us - packet_timestamp_us) as f64 / 1000.0);
  102. waiting_queue.remove(&seq_no);
  103. received += 1;
  104. }
  105. }
  106. }
  107. waiting_queue.retain(|seq, from| {
  108. if (timestamp - *from).as_secs() < timeout {
  109. true
  110. } else {
  111. println!("From {} icmp_seq={} timeout", remote_addr, seq);
  112. false
  113. }
  114. });
  115. if seq_no == count as u16 && waiting_queue.is_empty() {
  116. break
  117. }
  118. }
  119. let timestamp = utils::millis_since(startup_time);
  120. let poll_at = iface.poll(&mut sockets, timestamp).expect("poll error");
  121. let resume_at = [poll_at, Some(send_at)].iter().flat_map(|x| *x).min();
  122. phy_wait(fd, resume_at.map(|at| at.saturating_sub(timestamp))).expect("wait error");
  123. }
  124. println!("--- {} ping statistics ---", remote_addr);
  125. println!("{} packets transmitted, {} received, {:.0}% packet loss",
  126. seq_no, received, 100.0 * (seq_no - received) as f64 / seq_no as f64);
  127. }