Crate crab_nat

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§

natpmp
pcp

Structs§

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

Enums§

InternetProtocol
Specifies the protocol to map a port for. Values are defined to match the opcodes in the NAT-PMP RFC, here https://www.rfc-editor.org/rfc/rfc6886#section-3.3.
MappingFailure
Errors that occur during the respective port mapping protocols.
PortMappingType
Specifies a port mapping protocol, as well as any protocol specific parameters.
VersionCode
8-bit version field in the NAT-PMP and PCP headers.

Constants§

GATEWAY_PORT
The required port for NAT-PMP and its successor, PCP.
RECOMMENDED_MAPPING_LIFETIME_SECONDS
The RFC recommended lifetime for a port mapping, https://www.rfc-editor.org/rfc/rfc6886#section-3.3 page 12.