Created
March 23, 2018 14:17
-
-
Save berkus/7b2cc186bb89763c5f2dee907e3fe215 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// From https://pastebin.com/m8JMuTWz | |
extern crate pnet; | |
// use getopts::Options; | |
use std::env; | |
use std::net::{IpAddr, Ipv4Addr}; | |
use std::str::FromStr; | |
use pnet::transport::TransportChannelType::Layer4; | |
use pnet::transport::TransportProtocol::Ipv4; | |
use pnet::transport::{transport_channel, ipv4_packet_iter}; | |
use pnet::packet::icmp::{MutableIcmpPacket, IcmpTypes, echo_reply, echo_request, self}; | |
use pnet::packet::ip::IpNextHeaderProtocols; | |
fn create_ping_packet<'a>(sequence_number: u16) -> echo_request::MutableEchoRequestPacket<'a> { | |
let mut packet_contents = [0; 48]; | |
let mut ping_packet = echo_request::MutableEchoRequestPacket::new(&mut packet_contents[20..]).unwrap(); | |
ping_packet.set_icmp_type(IcmpTypes::EchoRequest); | |
ping_packet.set_icmp_code(echo_request::IcmpCodes::NoCode); | |
ping_packet.set_identifier(902); | |
ping_packet.set_sequence_number(sequence_number); | |
ping_packet.set_payload(b"Ring ring"); | |
ping_packet | |
} | |
fn main() { | |
let args: Vec<String> = env::args().collect(); | |
let host = args[args.len() - 1].clone(); | |
let ip_address = IpAddr::V4(Ipv4Addr::from_str(&host).unwrap()); | |
// TODO: Command line arguement checking | |
// let mut opts = Options::new(); | |
// opts.optopt("o", "", "set output file name", "NAME"); | |
// opts.optflag("h", "help", "print this help menu"); | |
// let matches = match opts.parse(&args[1..]) { | |
// Ok(m) => { m } | |
// Err(f) => { panic!(f.to_string()) } | |
// }; | |
let icmp_protocol = Layer4(Ipv4(IpNextHeaderProtocols::Icmp)); | |
let buffer_size = 4096; | |
let (mut t_sender, mut t_receiver) = match transport_channel(buffer_size, icmp_protocol) { | |
Ok((t_sender, t_receiver)) => (t_sender, t_receiver), | |
Err(err) => panic!("{:?}", err), | |
}; | |
let mut sequence_number = 0; | |
loop { | |
let mut iter = ipv4_packet_iter(&mut t_receiver); | |
let packet = create_ping_packet(sequence_number); | |
match t_sender.send_to(packet, ip_address) { | |
Ok(_) => println!("Sent"), | |
Err(e) => panic!("{}", e), | |
} | |
match iter.next() { | |
Ok((packet, _)) => println!("Received"), | |
Err(e) => println!("{}", e), | |
} | |
sequence_number += 1; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, may I ask why using
Layer4
in the protocol instead ofLayer3
which IP actually works on?