#udp-socket #sockets #udp #multicast #ip-address #ip-pktinfo #udp-packet

socket-pktinfo

Small library to allow cross-platform handling of IP_PKTINFO and IPV6_PKTINFO with socket2 crate

3 unstable releases

0.2.1 Mar 27, 2024
0.2.0 Mar 27, 2024
0.1.0 Mar 19, 2024

#1955 in Network programming

Download history 122/week @ 2024-03-15 180/week @ 2024-03-22 79/week @ 2024-03-29 8/week @ 2024-04-05

59 downloads per month

MIT license

22KB
425 lines

socket-pktinfo

Build Cargo docs.rs Rust version: 1.63+

Small library to allow cross-platform handling of IP_PKTINFO and IPV6_PKTINFO with socket2 crate. Primary use case for this crate is to determine if a UDP packet was sent to a unicast, broadcast or multicast IP address. Compatible with Windows, Linux and macOS.

Example

use std::net::{Ipv4Addr, SocketAddrV4};
use socket2::{Domain, SockAddr};
use socket_pktinfo::PktInfoUdpSocket;

fn main() -> std::io::Result<()> {

    let mut buf = [0; 1024];
    let mut socket = PktInfoUdpSocket::new(Domain::IPV4)?;
    socket.bind(&SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 8000).into())?;
        
    match socket.recv(&mut buf) {//!
         Ok((bytes_received, info)) => {
             println!("{} bytes received on interface index {} from src {} with destination ip {}",
              bytes_received, info.if_index, info.addr_src, info.addr_dst);
         }
         Err(e) => {
             eprintln!("Error receiving packet - {}", e);
         }
    }
     
    Ok(())
}

Dependencies

~0.2–8.5MB
~68K SLoC