ping.rs 9.2 KB

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