rping/src/main.rs

295 lines
11 KiB
Rust

// Import libs
mod libs;
// mod test;
// fn main() {
// // Parse the command line arguments.
// let res = libs::generate_ping_request(libs::parse_all_arguments());
// match res {
// Ok(()) => (),
// Err(()) => eprintln!("Program exited with errors")
// }
// }
// use pnet::packet::icmp::{
// echo_reply::EchoReplyPacket, echo_request::MutableEchoRequestPacket, IcmpTypes,
// };
// use pnet::packet::ip::IpNextHeaderProtocols::Icmp;
// use pnet::packet::Packet;
// use pnet_transport::{
// icmp_packet_iter, transport_channel, TransportChannelType::Layer4, TransportProtocol::Ipv4,
// };
// use pnet::util::checksum;
// use std::net::{IpAddr, Ipv4Addr};
// use std::sync::atomic::{AtomicBool, Ordering};
// use std::sync::{Arc, Mutex};
// use std::time::{Duration, Instant};
// /// The ping function of this program
// pub fn main() {
// // Create a channel to send ping packets
// let (mut tx, mut rx) = match transport_channel(1500, Layer4(Ipv4(Icmp))) {
// Ok((tx, rx)) => (tx, rx),
// Err(e) => panic!("An error occurred when creating transport channel: {}", e),
// };
// // Typical ICMP packet size
// let mut payload = [0u8; 64];
// let input = Arc::new("192.168.1.3");
// // Iterate through received ping packets
// let dst = input.parse::<Ipv4Addr>().expect("");
// let mut recv = icmp_packet_iter(&mut rx);
// // Random identifier
// const IDENT_NUM: u16 = 111;
// const TTL: u8 = 64;
// let counter = Arc::new(Mutex::new(0));
// let packet_loss = Arc::new(Mutex::new(0));
// let time: Arc<Mutex<Vec<f64>>> = Arc::new(Mutex::new(Vec::new()));
// let stop = Arc::new(AtomicBool::from(false));
// // Mimicking the `ping` utility in unix
// println!(
// "PING {}: {}({}) data bytes",
// // See if input is a domain name or IP address, and output accordingly
// if input.to_string() == dst.to_string() {
// dst.to_string()
// } else {
// format!("{} ({})", input, dst)
// },
// payload.len(),
// payload.len() - 8
// );
// let mut ping = MutableEchoRequestPacket::new(&mut payload).unwrap();
// ping.set_icmp_type(IcmpTypes::EchoRequest);
// ping.set_payload(b"hello");
// ping.set_identifier(IDENT_NUM);
// ping.set_sequence_number(*counter.lock().unwrap());
// ping.set_checksum(checksum(ping.packet(), 1));
// let curr_time = Instant::now();
// tx.set_ttl(TTL).unwrap();
// tx.send_to(ping, std::net::IpAddr::V4(dst)).expect("");
// match recv.next() {
// Ok((pkt, addr)) => {
// let pong = EchoReplyPacket::new(pkt.packet()).unwrap();
// if pong.get_icmp_type() == IcmpTypes::EchoReply
// && pong.get_identifier() == IDENT_NUM
// && pong.get_sequence_number() == *counter.lock().unwrap()
// {
// let elapsed = curr_time.elapsed();
// *counter.lock().unwrap() += 1;
// time.lock()
// .unwrap()
// .push(elapsed.as_micros() as f64 / 1000 as f64);
// println!(
// "{} bytes from {}: icmp_seq={} ttl={} time={:.1} ms",
// payload.len() - 8,
// // Same as above
// if input.to_string() == addr.to_string() {
// addr.to_string()
// } else {
// format!("{} ({})", input, addr)
// },
// counter.lock().unwrap(),
// TTL,
// elapsed.as_micros() as f64 / 1000 as f64
// );
// } else {
// *packet_loss.lock().unwrap() += 1;
// }
// }
// Err(e) => eprintln!("Error: {} ", e),
// }
// }
use pnet::packet::ethernet::{EtherTypes, EthernetPacket, MutableEthernetPacket};
use pnet::packet::ipv4;
use pnet::packet::icmp;
use pnet::packet::Packet;
use pnet_datalink::{
self,
MacAddr
};
use pnet_transport::{
icmp_packet_iter, transport_channel, TransportChannelType::Layer4, TransportProtocol::Ipv4,
TransportChannelType::Layer3
};
use pnet::packet::ip::{
IpNextHeaderProtocols::Icmp,IpNextHeaderProtocols,
};
use std::net::{IpAddr, Ipv4Addr};
use pnet::packet::icmp::{
echo_reply::EchoReplyPacket, echo_request::MutableEchoRequestPacket, IcmpTypes,
};
fn main() {
// Get the default network interface
let interfaces = pnet_datalink::interfaces();
let interface = interfaces.into_iter().next().unwrap();
// let (mut tx, mut rx) = match transport_channel(1500, Layer3(IpNextHeaderProtocols::Udp)) {
let (mut tx, mut rx) = match transport_channel(1500, Layer3(pnet_packet::ip::IpNextHeaderProtocols::Ipv4)) {
// let (mut tx, mut rx) = match transport_channel(1500, Layer4(Ipv4(Icmp))) {
Ok((tx, rx)) => (tx, rx),
Err(e) => panic!("An error occurred when creating transport channel: {}", e),
};
// Get the IP address of the interface
let ip_addr = interface.ips.into_iter().next().unwrap();
// Calculate the checksum of the ping request packet
// let checksum = icmp::checksum(&[0; 0]);
let mut recv = icmp_packet_iter(&mut rx);
// Create a new mutable ICMP packet
// let mut binding = [4;64];
// let mut packet = icmp::MutableIcmpPacket::new(&mut binding).expect("Couldn't create packet");
// let mut packet = pnet_packet::ipv4::MutableIpv4Packet::new(&mut binding).expect("Couldn't create packet");
// // Set the ICMP packet type and code to the appropriate values for a ping request
// packet.set_icmp_type(icmp::IcmpTypes::EchoRequest);
// packet.set_icmp_code(pnet::packet::icmp::IcmpCode(0xaa));
// // let frozen = binding.clone();
// packet.set_checksum(pnet_packet::icmp::checksum(&packet.to_immutable()));
// // Get a `Packet` object representing the ping request packet
// let ping_request_packet = packet.packet();
// let IDENT_NUM: u16 = 111;
// Create a new mutable Ethernet packet containaing the ICMP packet
let mut binding = [3; 64+32];
let mut binding = [/*0x44 ,0xd4 ,0x53 ,0x93 ,0x8a ,0x90 ,0x54 ,0xaf ,0x97 ,0x4d ,0x13 ,0xbf ,0x08 ,0x00 ,*/0x45 ,0x00,
0x00 ,0x54 ,0xcd ,0xdf ,0x40 ,0x00 ,0x40 ,0x01 ,0xe9 ,0x74 ,0xc0 ,0xa8 ,0x01 ,0x03 ,0xc0 ,0xa8,
0x01 ,0x01 ,0x08 ,0x00 ,0xba ,0x4c ,0x00 ,0x02 ,0x00 ,0x02 ,0xed ,0x04 ,0x95 ,0x63 ,0x00 ,0x00,
0x00 ,0x00 ,0xf6 ,0x73 ,0x06 ,0x00 ,0x00 ,0x00 ,0x00 ,0x00 ,0x10 ,0x11 ,0x12 ,0x13 ,0x14 ,0x15,
0x16 ,0x17 ,0x18 ,0x19 ,0x1a ,0x1b ,0x1c ,0x1d ,0x1e ,0x1f ,0x20 ,0x21 ,0x22 ,0x23 ,0x24 ,0x25,
0x26 ,0x27 ,0x28 ,0x29 ,0x2a ,0x2b ,0x2c ,0x2d ,0x2e ,0x2f ,0x30 ,0x31 ,0x32 ,0x33 ,0x34 ,0x35, 0x36, 0x37];
// let mut ethernet_packet = MutableEthernetPacket::new(&mut binding).unwrap();
let mut ethernet_packet = pnet_packet::ipv4::MutableIpv4Packet::new(&mut binding).unwrap();
// ethernet_packet.set_icmp_type();
// Set the destination and source MAC addresses
// ethernet_packet.set_destination(interface.mac.unwrap().clone());
// // ethernet_packet.set_source(interface.mac.unwrap());
// IPv4
// ethernet_packet.set_version(4);
// ethernet_packet.set_header_length(5);
// ethernet_packet.set_dscp(0);
// ethernet_packet.set_ecn(0);
// ethernet_packet.set_ttl(64);
// ethernet_packet.set_identification(8);
// ethernet_packet.set_flags(1);
// ethernet_packet.set_next_level_protocol(pnet_packet::ip::IpNextHeaderProtocols::Ipv4);//pnet_packet::ip::IpNextHeaderProtocol(6));
// ethernet_packet.set_source("192.168.1.3".parse::<Ipv4Addr>().expect("Couldn't set destination"));
// ethernet_packet.set_destination("192.168.1.1".parse::<Ipv4Addr>().expect("Couldn't set destination"));
// ethernet_packet.set_checksum(ethernet_packet.get_checksum());
// println!("Lgh {}",ethernet_packet.get_total_length());
// ethernet_packet.set_total_length(110);
// // ethernet_packet.set_source(interface.mac.unwrap());
// Set the EtherType to indicate that the payload is an IP packet
// ethernet_packet.set_ethertype(pnet::packet::ethernet::EtherType(0x0000));
// Set the payload of the Ethernet packet to the ping request packet
// ethernet_packet.set_payload(ping_request_packet);
// Get an `EthernetPacket` object from the mutable Ethernet packet
let ethernet_frame = ethernet_packet.packet();
// Send the Ethernet frame using the `ethernet::EthernetPacket::send` function
let dst = "192.168.1.1".parse::<Ipv4Addr>().expect("");
println!("{:?} {:?}",ethernet_packet.packet(), ethernet_packet);
let res = tx.send_to(ethernet_packet, std::net::IpAddr::V4(dst));
println!("{:?}",res);
// match recv.next() {
// Ok((pkt, addr)) => {
// let pong = EchoReplyPacket::new(pkt.packet()).unwrap();
// if pong.get_icmp_type() == IcmpTypes::EchoReply
// && pong.get_identifier() == IDENT_NUM
// && pong.get_sequence_number() == 1
// {
// ()
// } else {
// ()
// }
// }
// Err(e) => eprintln!("Error: {} ", e),
// }
}
// use std::io;
// use std::os::unix::io::AsRawFd;
// use libc::{AF_PACKET, SOCK_RAW, socket, sockaddr, sendto};
// fn main() -> io::Result<()> {
// // Create a new raw socket
// let socket = unsafe {
// socket(
// AF_PACKET,
// SOCK_RAW,
// libc::ETH_P_ALL
// )
// };
// if socket < 0 {
// println!("Couldn't build socket");
// return Err(io::Error::last_os_error());
// }
// // Set the write timeout to None
// // (not possible with the libc crate, so we have to use blocking I/O)
// // Create a byte array containing the data to be sent
// let data = [1, 2, 3, 4, 5];
// // Call the send_to method, specifying the destination MAC address
// let num_bytes = unsafe {
// sendto(
// socket,
// data.as_ptr() as *const libc::c_void,
// data.len() as libc::size_t,
// 0,
// &sockaddr {
// sa_family: AF_PACKET as u16,
// sa_data: [
// libc::ETH_P_ALL as i8,
// 0,
// 0,
// 0,
// 6,
// 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 1],
// } as *const sockaddr,
// std::mem::size_of::<sockaddr>() as libc::socklen_t
// )
// };
// if num_bytes < 0 {
// println!("No bytes were sent");
// return Err(io::Error::last_os_error());
// }
// println!("Successfully wrote {} bytes to the socket at layer 2.", num_bytes);
// Ok(())
// }