ping.rs 6.6 KB

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