Skip to content

Instantly share code, notes, and snippets.

@ssrlive
Created April 23, 2024 11:44
Show Gist options
  • Save ssrlive/889804e6db719893e1b93c8cd323d2ca to your computer and use it in GitHub Desktop.
Save ssrlive/889804e6db719893e1b93c8cd323d2ca to your computer and use it in GitHub Desktop.
ICMP demo code
fn handle_icmp_echo_request(u: &ipstack::stream::IpStackUnknownTransport) -> Result<()> {
use etherparse::{IcmpEchoHeader, Icmpv4Header, Icmpv6Header, IpNumber};
assert!(u.ip_protocol() == IpNumber::ICMP || u.ip_protocol() == IpNumber::IPV6_ICMP);
if u.src_addr().is_ipv4() {
let (icmp_header, req_payload) = Icmpv4Header::from_slice(u.payload()).map_err(|e| Error::from(e.to_string()))?;
if let etherparse::Icmpv4Type::EchoRequest(req) = icmp_header.icmp_type {
log::info!("#0 ICMPv4 echo");
let echo = IcmpEchoHeader { id: req.id, seq: req.seq };
let mut resp = Icmpv4Header::new(etherparse::Icmpv4Type::EchoReply(echo));
resp.update_checksum(req_payload);
let mut payload = resp.to_bytes().to_vec();
payload.extend_from_slice(req_payload);
u.send(payload)?;
} else {
log::info!("#0 unhandled ICMPv4 - {:?}", icmp_header.icmp_type);
}
}
if u.src_addr().is_ipv6() {
let (icmp_header, req_payload) = Icmpv6Header::from_slice(u.payload()).map_err(|e| Error::from(e.to_string()))?;
if let etherparse::Icmpv6Type::EchoRequest(req) = icmp_header.icmp_type {
log::info!("#0 ICMPv6 echo");
let echo = IcmpEchoHeader { id: req.id, seq: req.seq };
let mut resp = Icmpv6Header::new(etherparse::Icmpv6Type::EchoReply(echo));
let (src, dst) = match (u.src_addr(), u.dst_addr()) {
(std::net::IpAddr::V6(src), std::net::IpAddr::V6(dst)) => (src.octets(), dst.octets()),
_ => unreachable!(),
};
resp.update_checksum(dst, src, req_payload)
.map_err(|e| Error::from(e.to_string()))?;
let mut payload = resp.to_bytes().to_vec();
payload.extend_from_slice(req_payload);
u.send(payload)?;
} else {
log::info!("#0 unhandled ICMPv6 - {:?}", icmp_header.icmp_type);
}
}
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment