ping.rs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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::cmp;
  11. use std::os::unix::io::AsRawFd;
  12. use smoltcp::time::{Duration, Instant};
  13. use smoltcp::phy::Device;
  14. use smoltcp::phy::wait as phy_wait;
  15. use smoltcp::wire::{EthernetAddress, IpAddress, IpCidr,
  16. Ipv4Address, Icmpv4Repr, Icmpv4Packet};
  17. use smoltcp::iface::{NeighborCache, EthernetInterfaceBuilder};
  18. use smoltcp::socket::{SocketSet, IcmpSocket, IcmpSocketBuffer, IcmpPacketMetadata, IcmpEndpoint};
  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 device_caps = device.capabilities();
  38. let address = Ipv4Address::from_str(&matches.free[0]).expect("invalid address format");
  39. let count = matches.opt_str("count").map(|s| usize::from_str(&s).unwrap()).unwrap_or(4);
  40. let interval = matches.opt_str("interval")
  41. .map(|s| Duration::from_secs(u64::from_str(&s).unwrap()))
  42. .unwrap_or(Duration::from_secs(1));
  43. let timeout = Duration::from_secs(
  44. matches.opt_str("timeout").map(|s| u64::from_str(&s).unwrap()).unwrap_or(5)
  45. );
  46. let neighbor_cache = NeighborCache::new(BTreeMap::new());
  47. let remote_addr = address;
  48. let local_addr = Ipv4Address::new(192, 168, 69, 1);
  49. let icmp_rx_buffer = IcmpSocketBuffer::new(vec![IcmpPacketMetadata::empty()], vec![0; 256]);
  50. let icmp_tx_buffer = IcmpSocketBuffer::new(vec![IcmpPacketMetadata::empty()], vec![0; 256]);
  51. let icmp_socket = IcmpSocket::new(icmp_rx_buffer, icmp_tx_buffer);
  52. let ethernet_addr = EthernetAddress([0x02, 0x00, 0x00, 0x00, 0x00, 0x02]);
  53. let ip_addr = IpCidr::new(IpAddress::from(local_addr), 24);
  54. let default_v4_gw = Ipv4Address::new(192, 168, 69, 100);
  55. let mut iface = EthernetInterfaceBuilder::new(device)
  56. .ethernet_addr(ethernet_addr)
  57. .ip_addrs([ip_addr])
  58. .ipv4_gateway(default_v4_gw)
  59. .neighbor_cache(neighbor_cache)
  60. .finalize();
  61. let mut sockets = SocketSet::new(vec![]);
  62. let icmp_handle = sockets.add(icmp_socket);
  63. let mut send_at = Instant::from_millis(0);
  64. let mut seq_no = 0;
  65. let mut received = 0;
  66. let mut echo_payload = [0xffu8; 40];
  67. let mut waiting_queue = HashMap::new();
  68. let ident = 0x22b;
  69. let endpoint = IpAddress::Ipv4(remote_addr);
  70. loop {
  71. iface.poll(&mut sockets, Instant::now()).unwrap();
  72. {
  73. let timestamp = Instant::now();
  74. let mut socket = sockets.get::<IcmpSocket>(icmp_handle);
  75. if !socket.is_open() {
  76. socket.bind(IcmpEndpoint::Ident(ident)).unwrap();
  77. send_at = timestamp;
  78. }
  79. if socket.can_send() && seq_no < count as u16 &&
  80. send_at <= timestamp {
  81. NetworkEndian::write_i64(&mut echo_payload, timestamp.total_millis());
  82. let icmp_repr = Icmpv4Repr::EchoRequest {
  83. ident: ident,
  84. seq_no,
  85. data: &echo_payload,
  86. };
  87. let icmp_payload = socket
  88. .send(icmp_repr.buffer_len(), endpoint)
  89. .unwrap();
  90. let mut icmp_packet = Icmpv4Packet::new(icmp_payload);
  91. icmp_repr.emit(&mut icmp_packet, &device_caps.checksum);
  92. waiting_queue.insert(seq_no, timestamp);
  93. seq_no += 1;
  94. send_at += interval;
  95. }
  96. if socket.can_recv() {
  97. let (payload, _) = socket.recv().unwrap();
  98. let icmp_packet = Icmpv4Packet::new(&payload);
  99. let icmp_repr = Icmpv4Repr::parse(&icmp_packet, &device_caps.checksum).unwrap();
  100. if let Icmpv4Repr::EchoReply { seq_no, data, .. } = icmp_repr {
  101. if let Some(_) = waiting_queue.get(&seq_no) {
  102. let packet_timestamp_ms = NetworkEndian::read_i64(data);
  103. println!("{} bytes from {}: icmp_seq={}, time={}ms",
  104. data.len(), remote_addr, seq_no,
  105. timestamp.total_millis() - packet_timestamp_ms);
  106. waiting_queue.remove(&seq_no);
  107. received += 1;
  108. }
  109. }
  110. }
  111. waiting_queue.retain(|seq, from| {
  112. if timestamp - *from < 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 = Instant::now();
  124. match iface.poll_at(&sockets, timestamp) {
  125. Some(poll_at) if timestamp < poll_at => {
  126. let resume_at = cmp::min(poll_at, send_at);
  127. phy_wait(fd, Some(resume_at - timestamp)).expect("wait error");
  128. },
  129. Some(_) => (),
  130. None => {
  131. phy_wait(fd, Some(send_at - timestamp)).expect("wait error");
  132. }
  133. }
  134. }
  135. println!("--- {} ping statistics ---", remote_addr);
  136. println!("{} packets transmitted, {} received, {:.0}% packet loss",
  137. seq_no, received, 100.0 * (seq_no - received) as f64 / seq_no as f64);
  138. }