diff --git a/.gitignore b/.gitignore index 3bb9346..f585d06 100644 --- a/.gitignore +++ b/.gitignore @@ -14,4 +14,5 @@ Cargo.lock # MSVC Windows builds of rustc generate these, which store debugging information *.pdb -pkts.txt \ No newline at end of file +pkts.txt +original.rs \ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml index 5357087..a98a80f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,16 +6,15 @@ edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -socket2 = { version = "0.4.7", features = ["all"] } -env_logger = "0.10" +#socket2 = { version = "0.4.7", features = ["all"] } +#env_logger = "0.10" rhexdump = "0.1.1" rand = "0.8.5" pnet = "0.31.0" pnet_datalink = "0.31.0" pnet_transport = "0.31.0" pnet_packet = "0.31.0" -libc = "0.2.138" - +#libc = "0.2.138" #dns-lookup = "1.0.8" [profile.release] diff --git a/src/libs.rs b/src/libs.rs index 04aad3c..9aa9d8b 100644 --- a/src/libs.rs +++ b/src/libs.rs @@ -1,8 +1,14 @@ mod icmp; mod args; +mod ipv4; pub use icmp::{ - generate_ping_request, - calculate_checksum + // generate_ping_request, + // calculate_checksum }; -pub use args::parse_all_arguments; \ No newline at end of file +pub use args::parse_all_arguments; +pub use ipv4::{ + create_ethernet_packet, + create_interface, + send_packet, +}; \ No newline at end of file diff --git a/src/libs/args.rs b/src/libs/args.rs index 76b8b6d..ffb325f 100644 --- a/src/libs/args.rs +++ b/src/libs/args.rs @@ -2,26 +2,47 @@ use std::env; pub struct Config{ pub dest_addr : String, + pub src_addr : String, pub ping_type : u8, pub identifier : u16, pub sequence : u16, pub payload : Vec, pub payload_size : usize, pub raw_packet : bool, + pub packet_size : u8, + pub ipv4_version : u8, + pub ihl : u8, + pub dcsp : u8, + pub ecn : u8, + pub ttl: u8, + pub identification : u16, + pub flags : u8, + pub offset : u16, } + pub fn parse_all_arguments() -> Config { // Load all inline arguments and create a config structure let args: Vec = env::args().collect(); let mut config = Config { dest_addr : String::new(), + src_addr : String::from("0.0.0.0"), ping_type : 0x08, identifier : 0x4242, sequence : 0x4242, payload: Vec::::new(), payload_size : 64, raw_packet: false, + ipv4_version: 4, + packet_size: 64, + ihl : 5, + dcsp : 0, + ecn : 0, + ttl : 64, + identification : 52703, + flags : 2, + offset: 0, }; if args.len() == 1 { exit_with_help(); diff --git a/src/libs/icmp.rs b/src/libs/icmp.rs index 7e30d63..866c141 100644 --- a/src/libs/icmp.rs +++ b/src/libs/icmp.rs @@ -1,248 +1,248 @@ -use crate::libs::args::Config; -use core::time::Duration; -use rand::{ - Rng, - thread_rng, - distributions::Alphanumeric, -}; -use std::time::Instant; +// use crate::libs::args::Config; +// use core::time::Duration; +// use rand::{ +// Rng, +// thread_rng, +// distributions::Alphanumeric, +// }; +// use std::time::Instant; -use std::{ - io::{self}, - net, - net::{IpAddr, Ipv4Addr, SocketAddr, ToSocketAddrs}, -}; -use std::os::{ - unix::io::AsRawFd, - unix::io::FromRawFd -}; +// use std::{ +// io::{self}, +// net, +// net::{IpAddr, Ipv4Addr, SocketAddr, ToSocketAddrs}, +// }; +// use std::os::{ +// unix::io::AsRawFd, +// unix::io::FromRawFd +// }; -struct SocketAddresses{ - socket1_addr: net::SocketAddr, - socket2_addr: socket2::SockAddr, - dest_addr: net::SocketAddr, -} -//use env_logger::Env; -pub fn generate_ping_request(config : crate::libs::args::Config) -> Result<(),()>{ - - let addr = create_addresses(&config.dest_addr); - let mut socket2_ipv4_socket=create_sockets(addr.socket1_addr, &addr.socket2_addr); - let socket_final = match config.raw_packet{ - true => create_socket_raw(&config, &mut socket2_ipv4_socket), - false => create_socket_udp(&mut socket2_ipv4_socket), - }; - - let (buffer, checksum) = create_buffer( - config.ping_type, - config.identifier, - config.sequence, - config.payload, - config.payload_size - ); - let buffer = [0xd8 ,0xcb ,0x8a ,0xc1 ,0x1b ,0xac ,0x54 ,0xaf ,0x97 ,0x4d ,0x13 ,0xbf ,0x08 ,0x00 ,0x45 ,0x00 - ,0x00 ,0x54 ,0x68 ,0xc4 ,0x40 ,0x00 ,0x40 ,0x01 ,0x4e ,0x84 ,0xc0 ,0xa8 ,0x01 ,0x03 ,0xc0 ,0xa8 - ,0x01 ,0x0d ,0x08 ,0x00 ,0xbe ,0x7a ,0x00 ,0x04 ,0x00 ,0x01 ,0x90 ,0x19 ,0x95 ,0x63 ,0x00 ,0x00 - ,0x00 ,0x00 ,0x47 ,0x30 ,0x0e ,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]; - // Send the ping request to the specified destination IP address. - print_send_pre_message(checksum, &buffer.to_vec()); - - socket_final.connect(&addr.socket2_addr).expect("Couldn't connect the socket to remote host"); - - // Starting the timer - let now = Instant::now(); - let result = socket_final.send_to(&buffer, &addr.socket2_addr); - // let result = socket_arc.send_to_with_flags(&buffer, dest_addr, 0); - - match result { - Ok(bytes) => print_send_post_messages(bytes, addr.dest_addr, checksum), - Err(err) => println!(" [ERROR] Failed to send data over the socket: {}", err) - } - - // Wait for a response from the destination. - // let mut buf = Vec::new(); - // buf.reserve(config.payload_size); // Make that buffer arbitrary large; - use std::mem::MaybeUninit; - let mut buf = Vec::>::new(); - let mut buff = MaybeUninit::>::uninit(); - buf.reserve(config.payload_size); - // unsafe { make_uninit_vec(v.as_mut_ptr(),config.payload_size); } - // let mut buf : socket2::MaybeUninitSlice = socket2::MaybeUninitSlice::from(buf); - let timeout = std::time::Duration::from_secs(1); - socket_final.set_nonblocking(false); - let bytes_recv=socket_final.recv(&mut buf); - - // socket_final.set_read_timeout(Some(timeout)).unwrap(); - // let (bytes_recv, _src_addr) = match socket_final.recv_from(&mut buf) { - // Ok(res) => res, - // Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { - // println!(" [ERROR] No response from destination"); - // println!(" [ERROR] {:?}", err); - // std::process::exit(0); - // } - // Err(err) => panic!(" [ERROR] Error receiving data: {}", err), - // }; - let elapsed = now.elapsed(); - - print_recv_post_message(&buf, bytes_recv.expect(""), elapsed); - Ok(()) -} - - -// fn make_uninit_vec(out: *mut Vec, size:usize) { - +// struct SocketAddresses{ +// socket1_addr: net::SocketAddr, +// socket2_addr: socket2::SockAddr, +// dest_addr: net::SocketAddr, // } -fn create_addresses(dest_ip: &String) -> SocketAddresses{ - // SOURCE IP ADDRESS - let localhost = Ipv4Addr::UNSPECIFIED; - let socket1_addr = SocketAddr::new(IpAddr::V4(localhost), 80); - let socket2_addr = socket1_addr.into(); +// //use env_logger::Env; +// pub fn generate_ping_request(config : crate::libs::args::Config) -> Result<(),()>{ - let dest_addr = ((*dest_ip).clone(),0).to_socket_addrs().unwrap().next().unwrap(); - SocketAddresses {socket1_addr, socket2_addr, dest_addr} -} +// let addr = create_addresses(&config.dest_addr); +// let mut socket2_ipv4_socket=create_sockets(addr.socket1_addr, &addr.socket2_addr); +// let socket_final = match config.raw_packet{ +// true => create_socket_raw(&config, &mut socket2_ipv4_socket), +// false => create_socket_udp(&mut socket2_ipv4_socket), +// }; -fn create_sockets(socket_ip_address:SocketAddr, socket2_ip_address: &socket2::SockAddr) -> socket2::Socket { - let socket2_ipv4_socket = socket2::Socket::new( - socket2::Domain::IPV4, - socket2::Type::RAW, - Some(socket2::Protocol::ICMPV4), - ).unwrap(); +// let (buffer, checksum) = create_buffer( +// config.ping_type, +// config.identifier, +// config.sequence, +// config.payload, +// config.payload_size +// ); +// let buffer = [0xd8 ,0xcb ,0x8a ,0xc1 ,0x1b ,0xac ,0x54 ,0xaf ,0x97 ,0x4d ,0x13 ,0xbf ,0x08 ,0x00 ,0x45 ,0x00 +// ,0x00 ,0x54 ,0x68 ,0xc4 ,0x40 ,0x00 ,0x40 ,0x01 ,0x4e ,0x84 ,0xc0 ,0xa8 ,0x01 ,0x03 ,0xc0 ,0xa8 +// ,0x01 ,0x0d ,0x08 ,0x00 ,0xbe ,0x7a ,0x00 ,0x04 ,0x00 ,0x01 ,0x90 ,0x19 ,0x95 ,0x63 ,0x00 ,0x00 +// ,0x00 ,0x00 ,0x47 ,0x30 ,0x0e ,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]; +// // Send the ping request to the specified destination IP address. +// print_send_pre_message(checksum, &buffer.to_vec()); - // BIND TO LOCAL ADDRESS - socket2_ipv4_socket - .bind(&socket2_ip_address) - .expect(&format!( - "Failed binding to Ipv4 address {:?}", - &socket_ip_address - )); +// socket_final.connect(&addr.socket2_addr).expect("Couldn't connect the socket to remote host"); - socket2_ipv4_socket -} +// // Starting the timer +// let now = Instant::now(); +// let result = socket_final.send_to(&buffer, &addr.socket2_addr); +// // let result = socket_arc.send_to_with_flags(&buffer, dest_addr, 0); -fn create_socket_udp(socket2_ipv4_socket: &mut socket2::Socket) -> socket2::Socket { - // CREATE STD SOCKET FROM SOCKET2 SOCKET - let raw_ipv4_socket = socket2_ipv4_socket.as_raw_fd(); - let std_ipv4_socket = unsafe { std::net::UdpSocket::from_raw_fd(raw_ipv4_socket) }; +// match result { +// Ok(bytes) => print_send_post_messages(bytes, addr.dest_addr, checksum), +// Err(err) => println!(" [ERROR] Failed to send data over the socket: {}", err) +// } - std_ipv4_socket - .set_read_timeout(Some(Duration::from_millis(100))) - .expect(&format!("Failed to set read timeout")); - socket2::Socket::from(std_ipv4_socket) - //Arc::new(std_ipv4_socket) -} +// // Wait for a response from the destination. +// // let mut buf = Vec::new(); +// // buf.reserve(config.payload_size); // Make that buffer arbitrary large; +// use std::mem::MaybeUninit; +// let mut buf = Vec::>::new(); +// let mut buff = MaybeUninit::>::uninit(); +// buf.reserve(config.payload_size); +// // unsafe { make_uninit_vec(v.as_mut_ptr(),config.payload_size); } +// // let mut buf : socket2::MaybeUninitSlice = socket2::MaybeUninitSlice::from(buf); +// let timeout = std::time::Duration::from_secs(1); +// socket_final.set_nonblocking(false); +// let bytes_recv=socket_final.recv(&mut buf); -fn create_socket_raw(config: &Config, _socket2_ipv4_socket: &mut socket2::Socket) -> socket2::Socket{ - let socket = match socket2::Socket::new_raw( - socket2::Domain::IPV4, - socket2::Type::RAW, - Some(socket2::Protocol::ICMPV4) - ){ - Err(error) => match error.kind() { - std::io::ErrorKind::PermissionDenied => { - println!("[ERROR] Raw socket require root privilege on your OS"); - std::process::exit(1); - }, - _ => panic!("Couldn't create raw socket {:?} ",error) - }, - Ok(res) => res, - }; - if config.raw_packet { match socket.set_header_included(true){ - Err(e) => panic!("Can't setup a raw packet via Socket2 options {}",e), - _ => (),}}; +// // socket_final.set_read_timeout(Some(timeout)).unwrap(); +// // let (bytes_recv, _src_addr) = match socket_final.recv_from(&mut buf) { +// // Ok(res) => res, +// // Err(ref err) if err.kind() == io::ErrorKind::WouldBlock => { +// // println!(" [ERROR] No response from destination"); +// // println!(" [ERROR] {:?}", err); +// // std::process::exit(0); +// // } +// // Err(err) => panic!(" [ERROR] Error receiving data: {}", err), +// // }; +// let elapsed = now.elapsed(); - socket.set_read_timeout(Some(Duration::from_millis(100))) - .expect(&format!("Failed to set read timeout")); - //Into::::into(socket); - //std::net::UdpSocket::from(socket) - socket -} +// print_recv_post_message(&buf, bytes_recv.expect(""), elapsed); +// Ok(()) +// } -fn create_buffer(ping_type: u8, identifier: u16, sequence: u16, mut payload: Vec, payload_size : usize) -> (Vec,u16){ - // Create the ping request message. - let mut buf = vec![0u8; payload_size]; - let header = [ - ping_type, 0x00, // Type and Code=0 fields - 0x00, 0x00, // Checksum (filled in later) - 0x00, 0x00, 0x00, 0x00, // Identifier and Sequence Number fields - ]; - buf[..header.len()].copy_from_slice(&header); - // Add the data to the ping request message. - let header = [ - (identifier >> 8) as u8, (identifier & 0xff) as u8, - (sequence >> 8) as u8, (sequence & 0xff) as u8, - ]; +// // fn make_uninit_vec(out: *mut Vec, size:usize) { - if payload.len() == 0{ - generate_payload(&mut payload, payload_size); - } - buf[header.len()..(header.len() + header.len())].copy_from_slice(&header); - buf[header.len() + header.len()..(header.len() + header.len()+payload.len())].copy_from_slice(&payload); +// // } +// fn create_addresses(dest_ip: &String) -> SocketAddresses{ +// // SOURCE IP ADDRESS +// let localhost = Ipv4Addr::UNSPECIFIED; +// let socket1_addr = SocketAddr::new(IpAddr::V4(localhost), 80); +// let socket2_addr = socket1_addr.into(); - // Calculate the checksum of the ping request message. - let checksum = calculate_checksum(&buf); - buf[2] = (checksum >> 8) as u8; - buf[3] = (checksum & 0xff) as u8; - (buf, checksum) -} +// let dest_addr = ((*dest_ip).clone(),0).to_socket_addrs().unwrap().next().unwrap(); +// SocketAddresses {socket1_addr, socket2_addr, dest_addr} +// } -pub fn calculate_checksum(buf : &Vec) -> u16 { - let checksum = { - let mut sum = 0; - for i in 0..(buf.len() / 2) { - sum += (buf[2 * i+1 ] as usize) << 8 | buf[2 * i] as usize; - } - if buf.len()%2==1 { sum += buf[buf.len()-1] as usize; } - while sum>>16!=0 { sum = (sum & 0xffff) + (sum >> 16) } - !(sum as u16) - }; - checksum -} +// fn create_sockets(socket_ip_address:SocketAddr, socket2_ip_address: &socket2::SockAddr) -> socket2::Socket { +// let socket2_ipv4_socket = socket2::Socket::new( +// socket2::Domain::IPV4, +// socket2::Type::RAW, +// Some(socket2::Protocol::ICMPV4), +// ).unwrap(); -fn print_send_pre_message(_checksum:u16, buffer:&Vec){ - println!("[SENDING ICMP DATA]\n"); - println!(" TY C0 CHECK ID SQ PAYLOAD----------> "); - println!("{}",rhexdump::hexdump(&buffer)); -} +// // BIND TO LOCAL ADDRESS +// socket2_ipv4_socket +// .bind(&socket2_ip_address) +// .expect(&format!( +// "Failed binding to Ipv4 address {:?}", +// &socket_ip_address +// )); -fn print_send_post_messages(bytes:usize, dest_addr:std::net::SocketAddr, checksum:u16){ - println!(" > Checksum [{:02x} {:02x}] - {} bytes sent to {}", (checksum&0xff00)>>8, (checksum)&0xff, bytes, dest_addr); -} +// socket2_ipv4_socket +// } -fn print_recv_post_message(buf: &Vec>, bytes_recv:usize, elapsed:Duration){ - // Parse the response from the destination. - // unsafe {buf.assume_init()}; - println!("Received {} bytes in {:?} {:?}",bytes_recv, elapsed, buf); - // let icmp_type = buf[0]; - // let icmp_code = buf[1]; - // let icmp_checksum = ((buf[2] as u16) << 8) | (buf[3] as u16); - // let icmp_id = ((buf[4] as u16) << 8) | (buf[5] as u16); - // let icmp_seq = ((buf[6] as u16) << 8) | (buf[7] as u16); - // //let data = &buf[8..bytes_recv]; +// fn create_socket_udp(socket2_ipv4_socket: &mut socket2::Socket) -> socket2::Socket { +// // CREATE STD SOCKET FROM SOCKET2 SOCKET +// let raw_ipv4_socket = socket2_ipv4_socket.as_raw_fd(); +// let std_ipv4_socket = unsafe { std::net::UdpSocket::from_raw_fd(raw_ipv4_socket) }; + +// std_ipv4_socket +// .set_read_timeout(Some(Duration::from_millis(100))) +// .expect(&format!("Failed to set read timeout")); +// socket2::Socket::from(std_ipv4_socket) +// //Arc::new(std_ipv4_socket) +// } - // // Print the parsed response. - // println!("\n[RECEIVING ICMP DATA] \n"); - // println!(" TY C0 CHECK ID SQ PAYLOAD----------> "); - // // println!("CHECKSUM: {:02x} {:02x}", (icmp_checksum&0xff00)>>8, (icmp_checksum)&0xff); - // println!("{}",rhexdump::hexdump(&buf)); - // println!(" > Checksum [{:02x} {:02x}] - \ - // {} bytes recv over the socket in {:.2} milliseconds", - // (icmp_checksum)>>8, (icmp_checksum)&0xff, - // bytes_recv, (elapsed.as_micros() as f64)/1000. - // ); - // println!(" > icmp_type = {:width$} icmp_code = {:width$}", icmp_type, icmp_code, width=2); - // println!(" > icmp_id = {:width$} icmp_seq = {:width$}", icmp_id, icmp_seq, width=2); - // println!(); -} +// fn create_socket_raw(config: &Config, _socket2_ipv4_socket: &mut socket2::Socket) -> socket2::Socket{ +// let socket = match socket2::Socket::new_raw( +// socket2::Domain::IPV4, +// socket2::Type::RAW, +// Some(socket2::Protocol::ICMPV4) +// ){ +// Err(error) => match error.kind() { +// std::io::ErrorKind::PermissionDenied => { +// println!("[ERROR] Raw socket require root privilege on your OS"); +// std::process::exit(1); +// }, +// _ => panic!("Couldn't create raw socket {:?} ",error) +// }, +// Ok(res) => res, +// }; +// if config.raw_packet { match socket.set_header_included(true){ +// Err(e) => panic!("Can't setup a raw packet via Socket2 options {}",e), +// _ => (),}}; -fn generate_payload(payload: &mut Vec,size:usize){ - // Generate a payload of size lenght - let mut rng = thread_rng(); - for _ in 0..(size-10){ - payload.push(rng.sample(Alphanumeric) as u8); - } -} \ No newline at end of file +// socket.set_read_timeout(Some(Duration::from_millis(100))) +// .expect(&format!("Failed to set read timeout")); +// //Into::::into(socket); +// //std::net::UdpSocket::from(socket) +// socket +// } + +// fn create_buffer(ping_type: u8, identifier: u16, sequence: u16, mut payload: Vec, payload_size : usize) -> (Vec,u16){ +// // Create the ping request message. +// let mut buf = vec![0u8; payload_size]; +// let header = [ +// ping_type, 0x00, // Type and Code=0 fields +// 0x00, 0x00, // Checksum (filled in later) +// 0x00, 0x00, 0x00, 0x00, // Identifier and Sequence Number fields +// ]; +// buf[..header.len()].copy_from_slice(&header); + +// // Add the data to the ping request message. +// let header = [ +// (identifier >> 8) as u8, (identifier & 0xff) as u8, +// (sequence >> 8) as u8, (sequence & 0xff) as u8, +// ]; + +// if payload.len() == 0{ +// generate_payload(&mut payload, payload_size); +// } +// buf[header.len()..(header.len() + header.len())].copy_from_slice(&header); +// buf[header.len() + header.len()..(header.len() + header.len()+payload.len())].copy_from_slice(&payload); + +// // Calculate the checksum of the ping request message. +// let checksum = calculate_checksum(&buf); +// buf[2] = (checksum >> 8) as u8; +// buf[3] = (checksum & 0xff) as u8; +// (buf, checksum) +// } + +// pub fn calculate_checksum(buf : &Vec) -> u16 { +// let checksum = { +// let mut sum = 0; +// for i in 0..(buf.len() / 2) { +// sum += (buf[2 * i+1 ] as usize) << 8 | buf[2 * i] as usize; +// } +// if buf.len()%2==1 { sum += buf[buf.len()-1] as usize; } +// while sum>>16!=0 { sum = (sum & 0xffff) + (sum >> 16) } +// !(sum as u16) +// }; +// checksum +// } + +// fn print_send_pre_message(_checksum:u16, buffer:&Vec){ +// println!("[SENDING ICMP DATA]\n"); +// println!(" TY C0 CHECK ID SQ PAYLOAD----------> "); +// println!("{}",rhexdump::hexdump(&buffer)); +// } + +// fn print_send_post_messages(bytes:usize, dest_addr:std::net::SocketAddr, checksum:u16){ +// println!(" > Checksum [{:02x} {:02x}] - {} bytes sent to {}", (checksum&0xff00)>>8, (checksum)&0xff, bytes, dest_addr); +// } + +// fn print_recv_post_message(buf: &Vec>, bytes_recv:usize, elapsed:Duration){ +// // Parse the response from the destination. +// // unsafe {buf.assume_init()}; +// println!("Received {} bytes in {:?} {:?}",bytes_recv, elapsed, buf); +// // let icmp_type = buf[0]; +// // let icmp_code = buf[1]; +// // let icmp_checksum = ((buf[2] as u16) << 8) | (buf[3] as u16); +// // let icmp_id = ((buf[4] as u16) << 8) | (buf[5] as u16); +// // let icmp_seq = ((buf[6] as u16) << 8) | (buf[7] as u16); +// // //let data = &buf[8..bytes_recv]; + +// // // Print the parsed response. +// // println!("\n[RECEIVING ICMP DATA] \n"); +// // println!(" TY C0 CHECK ID SQ PAYLOAD----------> "); +// // // println!("CHECKSUM: {:02x} {:02x}", (icmp_checksum&0xff00)>>8, (icmp_checksum)&0xff); +// // println!("{}",rhexdump::hexdump(&buf)); +// // println!(" > Checksum [{:02x} {:02x}] - \ +// // {} bytes recv over the socket in {:.2} milliseconds", +// // (icmp_checksum)>>8, (icmp_checksum)&0xff, +// // bytes_recv, (elapsed.as_micros() as f64)/1000. +// // ); +// // println!(" > icmp_type = {:width$} icmp_code = {:width$}", icmp_type, icmp_code, width=2); +// // println!(" > icmp_id = {:width$} icmp_seq = {:width$}", icmp_id, icmp_seq, width=2); +// // println!(); +// } + +// fn generate_payload(payload: &mut Vec,size:usize){ +// // Generate a payload of size lenght +// let mut rng = thread_rng(); +// for _ in 0..(size-10){ +// payload.push(rng.sample(Alphanumeric) as u8); +// } +// } \ No newline at end of file diff --git a/src/libs/ipv4.rs b/src/libs/ipv4.rs new file mode 100644 index 0000000..629cb95 --- /dev/null +++ b/src/libs/ipv4.rs @@ -0,0 +1,152 @@ +// Create an Ipv4 connection and have it ready to send IPv4 packets + +use crate::libs::args::Config; +// 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, + TransportReceiver, + TransportSender, +}; +use pnet::packet::ip::{ + IpNextHeaderProtocols::Icmp,IpNextHeaderProtocols, +}; +use std::net::{IpAddr, Ipv4Addr}; +use pnet::packet::icmp::{ + echo_reply::EchoReplyPacket, echo_request::MutableEchoRequestPacket, IcmpTypes, +}; + + +// Takes a config structure and generate a wrapper Packet, note that it will need to be filled with a payload +pub fn create_ethernet_packet<'a>(config: &'a Config) -> ipv4::MutableIpv4Packet<'a>{ + + let (mut tx, rx) = match transport_channel(1500, Layer3(pnet_packet::ip::IpNextHeaderProtocols::Ipv4)) { + // let (mut tx, mut rx) = match transport_channel(1500, Layer4(Ipv4(Icmp))) { // Non Raw + Ok((tx, rx)) => (tx, rx), + Err(e) => panic!("An error occurred when creating transport channel: {}", e), + }; + + // The total length is dependent on the packed sent + let size_tot: u16 = (config.ihl*4 + config.packet_size).into(); //84; // ihl*4+packet_size + let binding = vec![0; size_tot as usize]; + let mut ethernet_packet = pnet_packet::ipv4::MutableIpv4Packet::owned(binding).unwrap(); + + // 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 rethernet_packet = pnet_packet::ipv4::MutableIpv4Packet::new(&mut binding).unwrap(); + + // IPv4 + ethernet_packet.set_total_length(size_tot); + ethernet_packet.set_version(config.ipv4_version); + ethernet_packet.set_header_length(config.ihl); + ethernet_packet.set_dscp(config.dcsp); + ethernet_packet.set_ecn(config.ecn); + ethernet_packet.set_ttl(config.ttl); + ethernet_packet.set_identification(config.identification); + ethernet_packet.set_flags(config.flags); + ethernet_packet.set_fragment_offset(config.offset); + ethernet_packet.set_next_level_protocol(pnet_packet::ip::IpNextHeaderProtocols::Icmp);//pnet_packet::ip::IpNextHeaderProtocol(6)); + + // Get the IP address of the interface + // let ip_addr = interface.ips.into_iter().next().unwrap(); + //config.src_addr.parse + ethernet_packet.set_source(config.src_addr.parse::().expect("Couldn't parse source address")); + ethernet_packet.set_destination(config.dest_addr.parse::().expect("Couldn't parse destination address")); + + ethernet_packet.set_checksum(ipv4::checksum(ðernet_packet.to_immutable())); + + + // Send the Ethernet frame using the `ethernet::EthernetPacket::send` function + // println!("{:?} {:?}",rethernet_packet.packet(), rethernet_packet); + // assert_eq!(rethernet_packet.packet(),[69, 0, 0, 84, 205, 223, 64, 0, 64, 1, 233, 116, 192, 168, 1, 3, 192, 168, 1, 1, 8, 0, 186, 76, 0, 2, 0, 2, 237, 4, 149, 99, 0, 0, 0, 0, 246, 115, 6, 0, 0, 0, 0, 0, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55]); + + // let res = tx.send_to(rethernet_packet, std::net::IpAddr::V4("192.168.1.1".parse::().expect("Couldn't parse source address"))); + // println!("{:?}",res); + + ethernet_packet + +} + +// Create a transmiter/receiver interface with the send_to, recv methods +pub fn create_interface(config: &Config) -> (TransportSender,TransportReceiver) { + // Get the default network interface // Should allow for selection + // let interfaces = pnet_datalink::interfaces(); + // let interface = interfaces.into_iter().next().unwrap(); + + let (tx, rx) = match transport_channel(1500, Layer3(pnet_packet::ip::IpNextHeaderProtocols::Ipv4)) { + // let (mut tx, mut rx) = match transport_channel(1500, Layer4(Ipv4(Icmp))) { // Non Raw + Ok((tx, rx)) => (tx, rx), + Err(e) => panic!("An error occurred when creating transport channel: {}", e), + }; + (tx,rx) +} + +pub fn send_packet(packet: ipv4::Ipv4Packet, mut interface: TransportSender, dst: Ipv4Addr) -> Result{ + let res = interface.send_to(packet, std::net::IpAddr::V4(dst)); + println!("{:?}",res); + res +} + +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), + }; + + + 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 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), + // } +} \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 5ad5d56..88a0a96 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,294 +1,133 @@ -// Import libs mod libs; +use std::net::{ + // IpAddr, + Ipv4Addr +}; // 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") -// } -// } + +fn main() { + // Parse the command line arguments. + let config = libs::parse_all_arguments(); + let packet = libs::create_ethernet_packet(&config); + let (rx, _tx) = libs::create_interface(&config); + let res = libs::send_packet(packet.to_immutable(),rx,config.dest_addr.parse::().expect("Couldn't parse the IpAddr")); + match res { + Ok(s) => println!("{:?}", s), + Err(e) => eprintln!("Program exited with errors {:?}",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, // }; -// 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))) { +// 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, 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), // }; -// // Typical ICMP packet size -// let mut payload = [0u8; 64]; -// let input = Arc::new("192.168.1.3"); +// // Get the IP address of the interface +// // let ip_addr = interface.ips.into_iter().next().unwrap(); -// // Iterate through received ping packets -// let dst = input.parse::().expect(""); -// let mut recv = icmp_packet_iter(&mut rx); +// // Calculate the checksum of the ping request packet +// // let checksum = icmp::checksum(&[0; 0]); +// // 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>> = 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 -// ); +// // 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 = [0; 84]; +// // 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 size: u16 = binding.len().try_into().unwrap(); +// let mut ethernet_packet = pnet_packet::ipv4::MutableIpv4Packet::new(&mut binding).unwrap(); +// // IPv4 +// ethernet_packet.set_total_length(size); +// 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(52703); +// ethernet_packet.set_flags(2); +// ethernet_packet.set_fragment_offset(0); +// ethernet_packet.set_next_level_protocol(pnet_packet::ip::IpNextHeaderProtocols::Icmp);//pnet_packet::ip::IpNextHeaderProtocol(6)); +// ethernet_packet.set_source("192.168.1.3".parse::().expect("Couldn't set destination")); +// ethernet_packet.set_destination("192.168.1.1".parse::().expect("Couldn't set destination")); - -// 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), -// } - -// } +// ethernet_packet.set_checksum(pnet::packet::ipv4::checksum(ðernet_packet.to_immutable())); -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::().expect("Couldn't set destination")); - // ethernet_packet.set_destination("192.168.1.1".parse::().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::().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::() 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(()) -// } +// // 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(); +// // assert_eq!([69, 0, 0, 84, 205, 223, 64, 0, 64, 1, 233, 116, 192, 168, 1, 3, 192, 168, 1, 1, 8, 0, 186, 76, 0, 2, 0, 2, 237, 4, 149, 99, 0, 0, 0, 0, 246, 115, 6, 0, 0, 0, 0, 0, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55],ethernet_packet.packet()); +// // Send the Ethernet frame using the `ethernet::EthernetPacket::send` function +// let dst = "192.168.1.1".parse::().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), +// // } +// } \ No newline at end of file