ping.rs 9.0 KB

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