Crate crab_nat

source ·
Expand description

§🦀 NAT

A library providing a pure Rust implementation of a client for both the NAT Port Mapping Protocol (NAT-PMP, RFC 6886) and the Port Control Protocol (PCP, RFC 6887). This library is intended to feel like high level, idiomatic Rust, while still maintaining a strong focus on performance. It is asynchronous and uses the tokio runtime to avoid blocking operations and to succinctly handle timeouts on UDP sockets.

§Usage

async {
    use std::{net::{IpAddr, Ipv4Addr}, num::NonZeroU16};
    use crab_nat::{InternetProtocol, PortMapping, PortMappingOptions};
    // Attempt a port mapping request through PCP first and fallback to NAT-PMP.
    let mapping = match PortMapping::new(
        IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)), /* Address of the PCP server, often a gateway or firewall */
        IpAddr::V4(Ipv4Addr::new(192, 168, 1, 167)), /* Address of our client, as seen by the gateway. Only strictly necessary for PCP */
        InternetProtocol::Tcp, /* Protocol to map */
        NonZeroU16::new(8080).unwrap(), /* Internal port, cannot be zero */
        PortMappingOptions::default(), /* Optional configuration values, including suggested external port and lifetimes */
    )
    .await
    {
        Ok(m) => m,
        Err(e) => return eprintln!("Failed to map port: {e:?}"),
    };

    // ...

    // Try to safely drop the mapping.
    if let Err((e, m)) = mapping.try_drop().await {
        eprintln!("Failed to drop mapping {}:{}->{}: {e:?}", m.gateway(), m.external_port(), m.internal_port());
    } else {
        println!("Successfully deleted the mapping...");
    }
};

Modules§

Structs§

  • A port mapping on the gateway. Should be renewed with .try_renew() and deleted from the gateway with .try_drop().
  • Optional configuration values for a port mapping request.
  • Configuration of the timing of UDP requests to the gateway.

Enums§

  • Specifies the protocol to map a port for.
  • Errors that occur during the respective port mapping protocols.
  • Specifies a port mapping protocol, as well as any protocol specific parameters.
  • 8-bit version field in the NAT-PMP and PCP headers.

Constants§