ping.rs 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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 = match device.capabilities().medium {
  99. Medium::Ethernet => {
  100. Config::new(EthernetAddress([0x02, 0x00, 0x00, 0x00, 0x00, 0x01]).into())
  101. }
  102. Medium::Ip => Config::new(smoltcp::wire::HardwareAddress::Ip),
  103. Medium::Ieee802154 => todo!(),
  104. };
  105. config.random_seed = rand::random();
  106. let mut iface = Interface::new(config, &mut device, Instant::now());
  107. iface.update_ip_addrs(|ip_addrs| {
  108. ip_addrs
  109. .push(IpCidr::new(IpAddress::v4(192, 168, 69, 1), 24))
  110. .unwrap();
  111. ip_addrs
  112. .push(IpCidr::new(IpAddress::v6(0xfdaa, 0, 0, 0, 0, 0, 0, 1), 64))
  113. .unwrap();
  114. ip_addrs
  115. .push(IpCidr::new(IpAddress::v6(0xfe80, 0, 0, 0, 0, 0, 0, 1), 64))
  116. .unwrap();
  117. });
  118. iface
  119. .routes_mut()
  120. .add_default_ipv4_route(Ipv4Address::new(192, 168, 69, 100))
  121. .unwrap();
  122. iface
  123. .routes_mut()
  124. .add_default_ipv6_route(Ipv6Address::new(0xfe80, 0, 0, 0, 0, 0, 0, 0x100))
  125. .unwrap();
  126. // Create sockets
  127. let icmp_rx_buffer = icmp::PacketBuffer::new(vec![icmp::PacketMetadata::EMPTY], vec![0; 256]);
  128. let icmp_tx_buffer = icmp::PacketBuffer::new(vec![icmp::PacketMetadata::EMPTY], vec![0; 256]);
  129. let icmp_socket = icmp::Socket::new(icmp_rx_buffer, icmp_tx_buffer);
  130. let mut sockets = SocketSet::new(vec![]);
  131. let icmp_handle = sockets.add(icmp_socket);
  132. let mut send_at = Instant::from_millis(0);
  133. let mut seq_no = 0;
  134. let mut received = 0;
  135. let mut echo_payload = [0xffu8; 40];
  136. let mut waiting_queue = HashMap::new();
  137. let ident = 0x22b;
  138. loop {
  139. let timestamp = Instant::now();
  140. iface.poll(timestamp, &mut device, &mut sockets);
  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(address) => {
  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. &iface.get_source_address_ipv6(&address),
  174. &address,
  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(address) => {
  201. let icmp_packet = Icmpv6Packet::new_checked(&payload).unwrap();
  202. let icmp_repr = Icmpv6Repr::parse(
  203. &address,
  204. &iface.get_source_address_ipv6(&address),
  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 {remote_addr} icmp_seq={seq} timeout");
  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!("--- {remote_addr} ping statistics ---");
  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. }