ping.rs 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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::{self, FromStr};
  9. use std::time::{Duration, Instant};
  10. use smoltcp::Error;
  11. use smoltcp::wire::{EthernetAddress, IpVersion, IpProtocol, IpAddress,
  12. Ipv4Address, Ipv4Packet, Ipv4Repr,
  13. Icmpv4Repr, Icmpv4Packet};
  14. use smoltcp::iface::{ArpCache, SliceArpCache, EthernetInterface};
  15. use smoltcp::socket::{AsSocket, SocketSet};
  16. use smoltcp::socket::{RawSocket, RawSocketBuffer, RawPacketBuffer};
  17. use std::collections::HashMap;
  18. use byteorder::{ByteOrder, NetworkEndian};
  19. fn main() {
  20. utils::setup_logging("warn");
  21. let (mut opts, mut free) = utils::create_options();
  22. utils::add_tap_options(&mut opts, &mut free);
  23. utils::add_middleware_options(&mut opts, &mut free);
  24. opts.optopt("c", "count", "Amount of echo request packets to send (default: 4)", "COUNT");
  25. opts.optopt("i", "interval",
  26. "Interval between successive packets sent (seconds) (default: 1)", "INTERVAL");
  27. opts.optopt("", "timeout",
  28. "Maximum wait duration for an echo response packet (seconds) (default: 5)",
  29. "TIMEOUT");
  30. free.push("ADDRESS");
  31. let mut matches = utils::parse_options(&opts, free);
  32. let device = utils::parse_tap_options(&mut matches);
  33. let device = utils::parse_middleware_options(&mut matches, device, /*loopback=*/false);
  34. let address = Ipv4Address::from_str(&matches.free[0]).expect("invalid address format");
  35. let count = matches.opt_str("count").map(|s| usize::from_str(&s).unwrap()).unwrap_or(4);
  36. let interval = matches.opt_str("interval").map(|s| u64::from_str(&s).unwrap()).unwrap_or(1);
  37. let timeout = matches.opt_str("timeout").map(|s| u64::from_str(&s).unwrap()).unwrap_or(5);
  38. let startup_time = Instant::now();
  39. let arp_cache = SliceArpCache::new(vec![Default::default(); 8]);
  40. let remote_addr = address;
  41. let local_addr = Ipv4Address::new(192, 168, 69, 1);
  42. let raw_rx_buffer = RawSocketBuffer::new(vec![RawPacketBuffer::new(vec![0; 256])]);
  43. let raw_tx_buffer = RawSocketBuffer::new(vec![RawPacketBuffer::new(vec![0; 256])]);
  44. let raw_socket = RawSocket::new(IpVersion::Ipv4, IpProtocol::Icmp,
  45. raw_rx_buffer, raw_tx_buffer);
  46. let hardware_addr = EthernetAddress([0x02, 0x00, 0x00, 0x00, 0x00, 0x02]);
  47. let mut iface = EthernetInterface::new(
  48. Box::new(device), Box::new(arp_cache) as Box<ArpCache>,
  49. hardware_addr, [IpAddress::from(local_addr)]);
  50. let mut sockets = SocketSet::new(vec![]);
  51. let raw_handle = sockets.add(raw_socket);
  52. let mut send_next = Duration::default();
  53. let mut seq_no = 0;
  54. let mut received = 0;
  55. let mut echo_payload = [0xffu8; 40];
  56. let mut waiting_queue = HashMap::new();
  57. loop {
  58. {
  59. let socket: &mut RawSocket = sockets.get_mut(raw_handle).as_socket();
  60. let timestamp = Instant::now().duration_since(startup_time);
  61. let timestamp_us = (timestamp.as_secs() * 1000000) +
  62. (timestamp.subsec_nanos() / 1000) as u64;
  63. if seq_no == count as u16 && waiting_queue.is_empty() {
  64. break;
  65. }
  66. if socket.can_send() && seq_no < count as u16 && send_next <= timestamp {
  67. NetworkEndian::write_u64(&mut echo_payload, timestamp_us);
  68. let icmp_repr = Icmpv4Repr::EchoRequest {
  69. ident: 1,
  70. seq_no,
  71. data: &echo_payload,
  72. };
  73. let ipv4_repr = Ipv4Repr {
  74. /*src_addr: Ipv4Address::UNSPECIFIED,*/
  75. src_addr: Ipv4Address::new(0, 0, 0, 0),
  76. dst_addr: remote_addr,
  77. protocol: IpProtocol::Icmp,
  78. payload_len: icmp_repr.buffer_len(),
  79. };
  80. let raw_payload = socket
  81. .send(ipv4_repr.buffer_len() + icmp_repr.buffer_len())
  82. .unwrap();
  83. let mut ipv4_packet = Ipv4Packet::new(raw_payload);
  84. ipv4_repr.emit(&mut ipv4_packet);
  85. let mut icmp_packet = Icmpv4Packet::new(ipv4_packet.payload_mut());
  86. icmp_repr.emit(&mut icmp_packet);
  87. waiting_queue.insert(seq_no, timestamp);
  88. seq_no += 1;
  89. send_next += Duration::new(interval, 0);
  90. }
  91. if socket.can_recv() {
  92. let payload = socket.recv().unwrap();
  93. let ipv4_packet = Ipv4Packet::new(payload);
  94. let ipv4_repr = Ipv4Repr::parse(&ipv4_packet).unwrap();
  95. if ipv4_repr.src_addr == remote_addr && ipv4_repr.dst_addr == local_addr {
  96. let icmp_packet = Icmpv4Packet::new(ipv4_packet.payload());
  97. let icmp_repr = Icmpv4Repr::parse(&icmp_packet);
  98. if let Ok(Icmpv4Repr::EchoReply { seq_no, data, .. }) = icmp_repr {
  99. if let Some(_) = waiting_queue.get(&seq_no) {
  100. let packet_timestamp_us = NetworkEndian::read_u64(data);
  101. println!("{} bytes from {}: icmp_seq={}, time={:.3}ms",
  102. data.len(), remote_addr, seq_no,
  103. (timestamp_us - packet_timestamp_us) as f64 / 1000.0);
  104. waiting_queue.remove(&seq_no);
  105. received += 1;
  106. }
  107. }
  108. }
  109. }
  110. waiting_queue.retain(|seq, from| {
  111. if (timestamp - *from).as_secs() < timeout {
  112. true
  113. } else {
  114. println!("From {} icmp_seq={} timeout", remote_addr, seq);
  115. false
  116. }
  117. })
  118. }
  119. let timestamp = Instant::now().duration_since(startup_time);
  120. let timestamp_ms = (timestamp.as_secs() * 1000) +
  121. (timestamp.subsec_nanos() / 1000000) as u64;
  122. match iface.poll(&mut sockets, timestamp_ms) {
  123. Ok(()) | Err(Error::Exhausted) => (),
  124. Err(e) => debug!("poll error: {}", e),
  125. }
  126. }
  127. println!("--- {} ping statistics ---", remote_addr);
  128. println!("{} packets transmitted, {} received, {:.0}% packet loss",
  129. seq_no, received, 100.0 * (seq_no - received) as f64 / seq_no as f64);
  130. }