ping.rs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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::time::Instant;
  10. use std::os::unix::io::AsRawFd;
  11. use smoltcp::phy::Device;
  12. use smoltcp::phy::wait as phy_wait;
  13. use smoltcp::wire::{EthernetAddress, IpVersion, IpProtocol, IpAddress, IpCidr,
  14. Ipv4Address, Ipv4Packet, Ipv4Repr,
  15. Icmpv4Repr, Icmpv4Packet};
  16. use smoltcp::iface::{ArpCache, SliceArpCache, EthernetInterface};
  17. use smoltcp::socket::{SocketSet, RawSocket, RawSocketBuffer, RawPacketBuffer};
  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 arp_cache = SliceArpCache::new(vec![Default::default(); 8]);
  43. let remote_addr = address;
  44. let local_addr = Ipv4Address::new(192, 168, 69, 1);
  45. let raw_rx_buffer = RawSocketBuffer::new(vec![RawPacketBuffer::new(vec![0; 256])]);
  46. let raw_tx_buffer = RawSocketBuffer::new(vec![RawPacketBuffer::new(vec![0; 256])]);
  47. let raw_socket = RawSocket::new(IpVersion::Ipv4, IpProtocol::Icmp,
  48. raw_rx_buffer, raw_tx_buffer);
  49. let ethernet_addr = EthernetAddress([0x02, 0x00, 0x00, 0x00, 0x00, 0x02]);
  50. let ip_addr = IpCidr::new(IpAddress::from(local_addr), 24);
  51. let default_v4_gw = Ipv4Address::new(192, 168, 69, 100);
  52. let mut iface = EthernetInterface::new(
  53. Box::new(device), Box::new(arp_cache) as Box<ArpCache>,
  54. ethernet_addr, [ip_addr], Some(default_v4_gw));
  55. let mut sockets = SocketSet::new(vec![]);
  56. let raw_handle = sockets.add(raw_socket);
  57. let mut send_at = 0;
  58. let mut seq_no = 0;
  59. let mut received = 0;
  60. let mut echo_payload = [0xffu8; 40];
  61. let mut waiting_queue = HashMap::new();
  62. loop {
  63. {
  64. let mut socket = sockets.get::<RawSocket>(raw_handle);
  65. let timestamp = Instant::now().duration_since(startup_time);
  66. let timestamp_us = (timestamp.as_secs() * 1000000) +
  67. (timestamp.subsec_nanos() / 1000) as u64;
  68. if socket.can_send() && seq_no < count as u16 &&
  69. send_at <= utils::millis_since(startup_time) {
  70. NetworkEndian::write_u64(&mut echo_payload, timestamp_us);
  71. let icmp_repr = Icmpv4Repr::EchoRequest {
  72. ident: 1,
  73. seq_no,
  74. data: &echo_payload,
  75. };
  76. let ipv4_repr = Ipv4Repr {
  77. /*src_addr: Ipv4Address::UNSPECIFIED,*/
  78. src_addr: Ipv4Address::new(0, 0, 0, 0),
  79. dst_addr: remote_addr,
  80. protocol: IpProtocol::Icmp,
  81. payload_len: icmp_repr.buffer_len(),
  82. ttl: 64
  83. };
  84. let raw_payload = socket
  85. .send(ipv4_repr.buffer_len() + icmp_repr.buffer_len())
  86. .unwrap();
  87. let mut ipv4_packet = Ipv4Packet::new(raw_payload);
  88. ipv4_repr.emit(&mut ipv4_packet, &device_caps.checksum);
  89. let mut icmp_packet = Icmpv4Packet::new(ipv4_packet.payload_mut());
  90. icmp_repr.emit(&mut icmp_packet, &device_caps.checksum);
  91. waiting_queue.insert(seq_no, timestamp);
  92. seq_no += 1;
  93. send_at += interval * 1000;
  94. }
  95. if socket.can_recv() {
  96. let payload = socket.recv().unwrap();
  97. let ipv4_packet = Ipv4Packet::new(payload);
  98. let ipv4_repr = Ipv4Repr::parse(&ipv4_packet, &device_caps.checksum).unwrap();
  99. if ipv4_repr.src_addr == remote_addr && ipv4_repr.dst_addr == local_addr {
  100. let icmp_packet = Icmpv4Packet::new(ipv4_packet.payload());
  101. let icmp_repr = Icmpv4Repr::parse(&icmp_packet, &device_caps.checksum);
  102. if let Ok(Icmpv4Repr::EchoReply { seq_no, data, .. }) = icmp_repr {
  103. if let Some(_) = waiting_queue.get(&seq_no) {
  104. let packet_timestamp_us = NetworkEndian::read_u64(data);
  105. println!("{} bytes from {}: icmp_seq={}, time={:.3}ms",
  106. data.len(), remote_addr, seq_no,
  107. (timestamp_us - packet_timestamp_us) as f64 / 1000.0);
  108. waiting_queue.remove(&seq_no);
  109. received += 1;
  110. }
  111. }
  112. }
  113. }
  114. waiting_queue.retain(|seq, from| {
  115. if (timestamp - *from).as_secs() < timeout {
  116. true
  117. } else {
  118. println!("From {} icmp_seq={} timeout", remote_addr, seq);
  119. false
  120. }
  121. });
  122. if seq_no == count as u16 && waiting_queue.is_empty() {
  123. break
  124. }
  125. }
  126. let timestamp = utils::millis_since(startup_time);
  127. let poll_at = iface.poll(&mut sockets, timestamp).expect("poll error");
  128. let resume_at = [poll_at, Some(send_at)].iter().flat_map(|x| *x).min();
  129. phy_wait(fd, resume_at.map(|at| at.saturating_sub(timestamp))).expect("wait error");
  130. }
  131. println!("--- {} ping statistics ---", remote_addr);
  132. println!("{} packets transmitted, {} received, {:.0}% packet loss",
  133. seq_no, received, 100.0 * (seq_no - received) as f64 / seq_no as f64);
  134. }