ping.rs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. mod utils;
  2. use byteorder::{ByteOrder, NetworkEndian};
  3. use log::debug;
  4. use std::cmp;
  5. use std::collections::BTreeMap;
  6. use std::collections::HashMap;
  7. use std::os::unix::io::AsRawFd;
  8. use std::str::FromStr;
  9. use smoltcp::iface::{InterfaceBuilder, NeighborCache, Routes};
  10. use smoltcp::phy::wait as phy_wait;
  11. use smoltcp::phy::Device;
  12. use smoltcp::socket::{IcmpEndpoint, IcmpPacketMetadata, IcmpSocket, IcmpSocketBuffer, SocketSet};
  13. use smoltcp::wire::{
  14. EthernetAddress, Icmpv4Packet, Icmpv4Repr, Icmpv6Packet, Icmpv6Repr, IpAddress, IpCidr,
  15. Ipv4Address, Ipv6Address,
  16. };
  17. use smoltcp::{
  18. phy::Medium,
  19. time::{Duration, Instant},
  20. };
  21. macro_rules! send_icmp_ping {
  22. ( $repr_type:ident, $packet_type:ident, $ident:expr, $seq_no:expr,
  23. $echo_payload:expr, $socket:expr, $remote_addr:expr ) => {{
  24. let icmp_repr = $repr_type::EchoRequest {
  25. ident: $ident,
  26. seq_no: $seq_no,
  27. data: &$echo_payload,
  28. };
  29. let icmp_payload = $socket.send(icmp_repr.buffer_len(), $remote_addr).unwrap();
  30. let icmp_packet = $packet_type::new_unchecked(icmp_payload);
  31. (icmp_repr, icmp_packet)
  32. }};
  33. }
  34. macro_rules! get_icmp_pong {
  35. ( $repr_type:ident, $repr:expr, $payload:expr, $waiting_queue:expr, $remote_addr:expr,
  36. $timestamp:expr, $received:expr ) => {{
  37. if let $repr_type::EchoReply { seq_no, data, .. } = $repr {
  38. if let Some(_) = $waiting_queue.get(&seq_no) {
  39. let packet_timestamp_ms = NetworkEndian::read_i64(data);
  40. println!(
  41. "{} bytes from {}: icmp_seq={}, time={}ms",
  42. data.len(),
  43. $remote_addr,
  44. seq_no,
  45. $timestamp.total_millis() - packet_timestamp_ms
  46. );
  47. $waiting_queue.remove(&seq_no);
  48. $received += 1;
  49. }
  50. }
  51. }};
  52. }
  53. fn main() {
  54. utils::setup_logging("warn");
  55. let (mut opts, mut free) = utils::create_options();
  56. utils::add_tuntap_options(&mut opts, &mut free);
  57. utils::add_middleware_options(&mut opts, &mut free);
  58. opts.optopt(
  59. "c",
  60. "count",
  61. "Amount of echo request packets to send (default: 4)",
  62. "COUNT",
  63. );
  64. opts.optopt(
  65. "i",
  66. "interval",
  67. "Interval between successive packets sent (seconds) (default: 1)",
  68. "INTERVAL",
  69. );
  70. opts.optopt(
  71. "",
  72. "timeout",
  73. "Maximum wait duration for an echo response packet (seconds) (default: 5)",
  74. "TIMEOUT",
  75. );
  76. free.push("ADDRESS");
  77. let mut matches = utils::parse_options(&opts, free);
  78. let device = utils::parse_tuntap_options(&mut matches);
  79. let fd = device.as_raw_fd();
  80. let device = utils::parse_middleware_options(&mut matches, device, /*loopback=*/ false);
  81. let device_caps = device.capabilities();
  82. let address = IpAddress::from_str(&matches.free[0]).expect("invalid address format");
  83. let count = matches
  84. .opt_str("count")
  85. .map(|s| usize::from_str(&s).unwrap())
  86. .unwrap_or(4);
  87. let interval = matches
  88. .opt_str("interval")
  89. .map(|s| Duration::from_secs(u64::from_str(&s).unwrap()))
  90. .unwrap_or_else(|| Duration::from_secs(1));
  91. let timeout = Duration::from_secs(
  92. matches
  93. .opt_str("timeout")
  94. .map(|s| u64::from_str(&s).unwrap())
  95. .unwrap_or(5),
  96. );
  97. let neighbor_cache = NeighborCache::new(BTreeMap::new());
  98. let remote_addr = address;
  99. let icmp_rx_buffer = IcmpSocketBuffer::new(vec![IcmpPacketMetadata::EMPTY], vec![0; 256]);
  100. let icmp_tx_buffer = IcmpSocketBuffer::new(vec![IcmpPacketMetadata::EMPTY], vec![0; 256]);
  101. let icmp_socket = IcmpSocket::new(icmp_rx_buffer, icmp_tx_buffer);
  102. let ethernet_addr = EthernetAddress([0x02, 0x00, 0x00, 0x00, 0x00, 0x02]);
  103. let src_ipv6 = IpAddress::v6(0xfdaa, 0, 0, 0, 0, 0, 0, 1);
  104. let ip_addrs = [
  105. IpCidr::new(IpAddress::v4(192, 168, 69, 1), 24),
  106. IpCidr::new(src_ipv6, 64),
  107. IpCidr::new(IpAddress::v6(0xfe80, 0, 0, 0, 0, 0, 0, 1), 64),
  108. ];
  109. let default_v4_gw = Ipv4Address::new(192, 168, 69, 100);
  110. let default_v6_gw = Ipv6Address::new(0xfe80, 0, 0, 0, 0, 0, 0, 0x100);
  111. let mut routes_storage = [None; 2];
  112. let mut routes = Routes::new(&mut routes_storage[..]);
  113. routes.add_default_ipv4_route(default_v4_gw).unwrap();
  114. routes.add_default_ipv6_route(default_v6_gw).unwrap();
  115. let medium = device.capabilities().medium;
  116. let mut builder = InterfaceBuilder::new(device)
  117. .ip_addrs(ip_addrs)
  118. .routes(routes);
  119. if medium == Medium::Ethernet {
  120. builder = builder
  121. .ethernet_addr(ethernet_addr)
  122. .neighbor_cache(neighbor_cache);
  123. }
  124. let mut iface = builder.finalize();
  125. let mut sockets = SocketSet::new(vec![]);
  126. let icmp_handle = sockets.add(icmp_socket);
  127. let mut send_at = Instant::from_millis(0);
  128. let mut seq_no = 0;
  129. let mut received = 0;
  130. let mut echo_payload = [0xffu8; 40];
  131. let mut waiting_queue = HashMap::new();
  132. let ident = 0x22b;
  133. loop {
  134. let timestamp = Instant::now();
  135. match iface.poll(&mut sockets, timestamp) {
  136. Ok(_) => {}
  137. Err(e) => {
  138. debug!("poll error: {}", e);
  139. }
  140. }
  141. {
  142. let timestamp = Instant::now();
  143. let mut socket = sockets.get::<IcmpSocket>(icmp_handle);
  144. if !socket.is_open() {
  145. socket.bind(IcmpEndpoint::Ident(ident)).unwrap();
  146. send_at = timestamp;
  147. }
  148. if socket.can_send() && seq_no < count as u16 && send_at <= timestamp {
  149. NetworkEndian::write_i64(&mut echo_payload, timestamp.total_millis());
  150. match remote_addr {
  151. IpAddress::Ipv4(_) => {
  152. let (icmp_repr, mut icmp_packet) = send_icmp_ping!(
  153. Icmpv4Repr,
  154. Icmpv4Packet,
  155. ident,
  156. seq_no,
  157. echo_payload,
  158. socket,
  159. remote_addr
  160. );
  161. icmp_repr.emit(&mut icmp_packet, &device_caps.checksum);
  162. }
  163. IpAddress::Ipv6(_) => {
  164. let (icmp_repr, mut icmp_packet) = send_icmp_ping!(
  165. Icmpv6Repr,
  166. Icmpv6Packet,
  167. ident,
  168. seq_no,
  169. echo_payload,
  170. socket,
  171. remote_addr
  172. );
  173. icmp_repr.emit(
  174. &src_ipv6,
  175. &remote_addr,
  176. &mut icmp_packet,
  177. &device_caps.checksum,
  178. );
  179. }
  180. _ => unimplemented!(),
  181. }
  182. waiting_queue.insert(seq_no, timestamp);
  183. seq_no += 1;
  184. send_at += interval;
  185. }
  186. if socket.can_recv() {
  187. let (payload, _) = socket.recv().unwrap();
  188. match remote_addr {
  189. IpAddress::Ipv4(_) => {
  190. let icmp_packet = Icmpv4Packet::new_checked(&payload).unwrap();
  191. let icmp_repr =
  192. Icmpv4Repr::parse(&icmp_packet, &device_caps.checksum).unwrap();
  193. get_icmp_pong!(
  194. Icmpv4Repr,
  195. icmp_repr,
  196. payload,
  197. waiting_queue,
  198. remote_addr,
  199. timestamp,
  200. received
  201. );
  202. }
  203. IpAddress::Ipv6(_) => {
  204. let icmp_packet = Icmpv6Packet::new_checked(&payload).unwrap();
  205. let icmp_repr = Icmpv6Repr::parse(
  206. &remote_addr,
  207. &src_ipv6,
  208. &icmp_packet,
  209. &device_caps.checksum,
  210. )
  211. .unwrap();
  212. get_icmp_pong!(
  213. Icmpv6Repr,
  214. icmp_repr,
  215. payload,
  216. waiting_queue,
  217. remote_addr,
  218. timestamp,
  219. received
  220. );
  221. }
  222. _ => unimplemented!(),
  223. }
  224. }
  225. waiting_queue.retain(|seq, from| {
  226. if timestamp - *from < timeout {
  227. true
  228. } else {
  229. println!("From {} icmp_seq={} timeout", remote_addr, seq);
  230. false
  231. }
  232. });
  233. if seq_no == count as u16 && waiting_queue.is_empty() {
  234. break;
  235. }
  236. }
  237. let timestamp = Instant::now();
  238. match iface.poll_at(&sockets, timestamp) {
  239. Some(poll_at) if timestamp < poll_at => {
  240. let resume_at = cmp::min(poll_at, send_at);
  241. phy_wait(fd, Some(resume_at - timestamp)).expect("wait error");
  242. }
  243. Some(_) => (),
  244. None => {
  245. phy_wait(fd, Some(send_at - timestamp)).expect("wait error");
  246. }
  247. }
  248. }
  249. println!("--- {} ping statistics ---", remote_addr);
  250. println!(
  251. "{} packets transmitted, {} received, {:.0}% packet loss",
  252. seq_no,
  253. received,
  254. 100.0 * (seq_no - received) as f64 / seq_no as f64
  255. );
  256. }