| 1 |
#![allow(dead_code)] |
| 2 |
|
| 3 |
use std::net::Ipv4Addr; |
| 4 |
|
| 5 |
use bitfield::bitfield; |
| 6 |
|
| 7 |
bitfield! { |
| 8 |
struct IpV4Header(MSB0 [u8]); |
| 9 |
impl Debug; |
| 10 |
u32; |
| 11 |
get_version, _: 3, 0; |
| 12 |
get_ihl, _: 7, 4; |
| 13 |
get_dscp, _: 13, 8; |
| 14 |
get_ecn, _: 15, 14; |
| 15 |
get_total_length, _: 31, 16; |
| 16 |
get_identification, _: 47, 32; |
| 17 |
get_df, _: 49; |
| 18 |
get_mf, _: 50; |
| 19 |
get_fragment_offset, _: 63, 51; |
| 20 |
get_time_to_live, _: 71, 64; |
| 21 |
get_protocol, _: 79, 72; |
| 22 |
get_header_checksum, _: 95, 80; |
| 23 |
u8, get_source_address, _: 103, 96, 4; |
| 24 |
u32, into Ipv4Addr, get_destination_address, _: 159, 128; |
| 25 |
} |
| 26 |
|
| 27 |
impl<T: AsRef<[u8]>> IpV4Header<T> { |
| 28 |
fn get_source_as_ip_addr(&self) -> Ipv4Addr { |
| 29 |
let mut src = [0; 4]; |
| 30 |
for (i, src) in src.iter_mut().enumerate() { |
| 31 |
*src = self.get_source_address(i); |
| 32 |
} |
| 33 |
src.into() |
| 34 |
} |
| 35 |
} |
| 36 |
|
| 37 |
fn main() { |
| 38 |
let data = [ |
| 39 |
0x45, 0x00, 0x00, 0x40, 0x69, 0x27, 0x40, 0x00, 0x40, 0x11, 0x4d, 0x0d, 0xc0, 0xa8, 0x01, |
| 40 |
0x2a, 0xc0, 0xa8, 0x01, 0xfe, |
| 41 |
]; |
| 42 |
|
| 43 |
let header = IpV4Header(data); |
| 44 |
|
| 45 |
assert_eq!(header.get_version(), 4); |
| 46 |
assert_eq!(header.get_total_length(), 64); |
| 47 |
assert_eq!(header.get_identification(), 0x6927); |
| 48 |
assert!(header.get_df()); |
| 49 |
assert!(!header.get_mf()); |
| 50 |
assert_eq!(header.get_fragment_offset(), 0); |
| 51 |
assert_eq!(header.get_protocol(), 0x11); |
| 52 |
println!( |
| 53 |
"from {} to {}", |
| 54 |
header.get_source_as_ip_addr(), |
| 55 |
header.get_destination_address() |
| 56 |
); |
| 57 |
|
| 58 |
println!("{:#?}", header); |
| 59 |
} |