socket_pktinfo/lib.rs
1//! Small library to allow cross-platform handling of IP_PKTINFO and IPV6_PKTINFO with socket2 crate.
2//!
3//! Primary use case for this crate is to determine if a UDP packet was sent to a unicast, broadcast or multicast IP address.
4//!
5//! Library implements a cross-platform wrapper [`crate::PktInfoUdpSocket`] around [`socket2::Socket`] which returns data extracted from
6//! the IP_PKTINFO and IPV6_PKTINFO control messages. Compatible with Windows, Linux and macOS.
7//!
8//! # Examples
9//!
10//! ```no_run
11//! use std::net::{Ipv4Addr, SocketAddrV4};
12//! use socket2::{Domain, SockAddr};
13//! use socket_pktinfo::PktInfoUdpSocket;
14//!
15//! # fn main() -> std::io::Result<()> {
16//!
17//! let mut buf = [0; 1024];
18//! let mut socket = PktInfoUdpSocket::new(Domain::IPV4)?;
19//! socket.bind(&SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 8000).into())?;
20//!
21//! match socket.recv(&mut buf) {//!
22//! Ok((bytes_received, info)) => {
23//! println!("{} bytes received on interface index {} from src {} with destination ip {}",
24//! bytes_received, info.if_index, info.addr_src, info.addr_dst);
25//! }
26//! Err(e) => {
27//! eprintln!("Error receiving packet - {}", e);
28//! }
29//! }
30//! # Ok(())
31//! # }
32//! ```
33
34#![allow(clippy::unnecessary_cast)]
35
36#[cfg(windows)]
37mod win;
38#[cfg(windows)]
39pub use win::*;
40
41#[cfg(not(windows))]
42mod unix;
43#[cfg(not(windows))]
44pub use unix::*;
45
46///
47#[derive(Debug, Clone)]
48pub struct PktInfo {
49 /// Interface index
50 pub if_index: u64,
51 /// Source address
52 pub addr_src: std::net::SocketAddr,
53 /// Header destination address
54 pub addr_dst: std::net::IpAddr,
55}