1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
/*!
# zero-packet
Super simple library to efficiently build and parse network packets in-place with zero overhead.
No async, no allocations, no dependencies, no macros, no std, no unsafe. It simply cannot be easier.
Use `zero-packet` if you are working with raw sockets.
Supported protocols:
- Ethernet
- ARP
- IPv4
- TCP
- UDP
- ICMP
## Getting started
Install via your command line:
```bash
cargo add zero-packet
```
Or add the following to your `Cargo.toml`:
```toml
[dependencies]
zero-packet = "0.0.1"
```
## PacketBuilder
If you want to create network packets manually and efficiently, look no further.
```Rust
// Raw packet that we will mutate in-place.
// Ethernet header (14 bytes) + IPv4 header (20 bytes) + UDP header (8 bytes) = 42 bytes.
let mut packet = [0u8; 53]
// Some random payload (11 bytes).
let payload = b"Hello, UDP!";
// PacketBuilder which holds a mutable reference to the byte slice.
let mut packet_builder = PacketBuilder::new(&mut packet);
// Sets Ethernet, IPv4 and UDP header fields.
// Optional: add payload to the packet.
// Encapsulates everything in the given byte slice.
packet_builder
.ethernet(src_mac, dest_mac, ethertype)?
.ipv4(version, ihl, dscp, ecn, total_length, id, flags, fragment_offset, ttl, protocol, src_ip, dest_ip)?
.udp(src_ip, src_port, dest_ip, dest_port, length)?
.payload(payload)?;
```
## PacketParser
Parsing any received byte slice for which we don't know ahead of time what type of packet it is.
```Rust
// Some byte slice that we have received.
// We don't know yet what it contains.
let packet = [..];
// PacketParser is a zero-copy packet parser.
// The `parse` method determines on its own what protocol headers are present.
// The method is strict about what input it accepts and validates certain fields.
let parsed = PacketParser::parse(&packet)?;
// Now it is as easy as this.
if let Some(ethernet) = parsed.ethernet {
let ethertype = ethernet.get_ethertype();
// ...
}
// Or this.
if let Some(ipv4) = parsed.ipv4 {
let src_ip = ipv4.get_src_ip();
// ...
}
// Alternatively, just parse headers directly manually.
// By adjusting the index of the slice you can find different headers.
if let Some(tcp) = TcpParser::new(&packet)? {
let src_port = tcp.get_src_port();
// ...
}
```
*/
// Disables the standard library.
#![no_std]
pub mod datalink;
pub mod misc;
pub mod network;
pub mod packet;
pub mod transport;