nattraversal

package module
v0.1.70001 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 8, 2026 License: MIT Imports: 14 Imported by: 0

README

go-nat-listener

A NAT traversal library for Go that provides standard network interfaces with automatic port mapping and renewal. This library enables applications running behind SOHO routers to accept incoming connections by automatically configuring port forwarding through UPnP and NAT-PMP protocols.

Features

  • Standard Go Network Interfaces: Drop-in replacements for net.Listen and net.ListenPacket
  • Automatic NAT Traversal: Supports UPnP and NAT-PMP protocols with automatic fallback
  • Port Renewal: Automatically renews port mappings to maintain connectivity
  • TCP and UDP Support: Works with both TCP listeners and UDP packet connections
  • External Address Discovery: Provides access to both internal and external network addresses
  • Structured Logging: Comprehensive structured logging via github.com/go-i2p/logger

Installation

go get github.com/go-i2p/go-nat-listener

Requirements

  • Go 1.24.5 or later
  • Router with UPnP or NAT-PMP support
  • Network environment allowing NAT traversal protocols

Quick Start

Note: This library only supports IPv4 networks. See Limitations for details.

TCP Listener
package main

import (
    "fmt"
    "log"
    "net"
    
    "github.com/go-i2p/go-nat-listener"
)

func main() {
    // Create a NAT-traversing TCP listener on port 8080
    listener, err := nattraversal.Listen(8080)
    if err != nil {
        log.Fatal("Failed to create listener:", err)
    }
    defer listener.Close()
    
    fmt.Printf("Listening on %s (external: %s)\n", 
        listener.Addr().(*nattraversal.NATAddr).InternalAddr(),
        listener.Addr().String())
    
    for {
        conn, err := listener.Accept()
        if err != nil {
            log.Printf("Accept error: %v", err)
            continue
        }
        
        go handleConnection(conn)
    }
}

func handleConnection(conn net.Conn) {
    defer conn.Close()
    // Handle the connection...
}
UDP Packet Listener
package main

import (
    "fmt"
    "log"
    "net"
    
    "github.com/go-i2p/go-nat-listener"
)

func main() {
    // Create a NAT-traversing UDP listener on port 9090
    listener, err := nattraversal.ListenPacket(9090)
    if err != nil {
        log.Fatal("Failed to create packet listener:", err)
    }
    defer listener.Close()
    
    fmt.Printf("UDP listening on %s (external: %s)\n",
        listener.Addr().(*nattraversal.NATAddr).InternalAddr(),
        listener.Addr().String())
    
    // Get the underlying PacketConn for reading/writing
    conn := listener.PacketConn()
    
    buffer := make([]byte, 1024)
    for {
        n, addr, err := conn.ReadFrom(buffer)
        if err != nil {
            log.Printf("Read error: %v", err)
            continue
        }
        
        fmt.Printf("Received %d bytes from %s: %s\n", n, addr, string(buffer[:n]))
    }
}
With Context (Timeout/Cancellation)
package main

import (
    "context"
    "fmt"
    "log"
    "time"
    
    "github.com/go-i2p/go-nat-listener"
)

func main() {
    // Create a context with a 10-second timeout for NAT discovery
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()
    
    // Create a NAT-traversing TCP listener with timeout
    listener, err := nattraversal.ListenContext(ctx, 8080)
    if err != nil {
        log.Fatal("Failed to create listener:", err)
    }
    defer listener.Close()
    
    fmt.Printf("Listening on external port: %d\n", listener.ExternalPort())
    
    // Accept connections normally...
}

API Reference

Core Functions
Listen(port int) (*NATListener, error)

Creates a TCP listener with NAT traversal on the specified port. Returns a NATListener that implements the standard net.Listener interface. This is a convenience wrapper around ListenContext using context.Background().

ListenContext(ctx context.Context, port int) (*NATListener, error)

Creates a TCP listener with NAT traversal on the specified port, with context support for cancellation and timeouts. The context can be used to cancel the discovery and mapping operations. Once the listener is created, the context is no longer used - use Close() to stop the listener.

ListenPacket(port int) (*NATPacketListener, error)

Creates a UDP packet listener with NAT traversal on the specified port. Returns a NATPacketListener for UDP communication. This is a convenience wrapper around ListenPacketContext using context.Background().

ListenPacketContext(ctx context.Context, port int) (*NATPacketListener, error)

Creates a UDP packet listener with NAT traversal on the specified port, with context support for cancellation and timeouts. The context can be used to cancel the discovery and mapping operations. Once the listener is created, the context is no longer used - use Close() to stop the listener.

ListenWithFallback(port int) (*NATListener, error)

Creates a TCP listener that attempts NAT traversal first, but falls back to a standard net.Listener if NAT traversal fails (e.g., when UPnP and NAT-PMP are both unavailable). This is useful when you want your application to work even in environments without NAT support. Use IsFallback() to check if fallback mode is active.

ListenWithFallbackContext(ctx context.Context, port int) (*NATListener, error)

Creates a TCP listener with fallback support and context for cancellation/timeouts.

ListenPacketWithFallback(port int) (*NATPacketListener, error)

Creates a UDP packet listener that attempts NAT traversal first, but falls back to a standard net.PacketConn if NAT traversal fails. Use IsFallback() to check if fallback mode is active.

ListenPacketWithFallbackContext(ctx context.Context, port int) (*NATPacketListener, error)

Creates a UDP packet listener with fallback support and context for cancellation/timeouts.

Types
NATListener

Implements net.Listener with automatic NAT traversal support:

  • Accept() (net.Conn, error) - Accepts incoming connections
  • Close() error - Closes the listener and stops port renewal
  • Addr() net.Addr - Returns the NAT-aware address
  • ExternalPort() int - Returns the external port number assigned by the NAT device (same as internal port in fallback mode)
  • IsFallback() bool - Returns true if NAT traversal failed and the listener is using a standard net.Listener without NAT hole-punching
NATPacketListener

Provides UDP packet listening with NAT traversal:

  • Accept() (net.PacketConn, error) - Returns the underlying packet connection. Unlike TCP's Accept() which blocks for new connections, this returns the same cached NATPacketConn instance each time (UDP is connectionless). Prefer using PacketConn() for direct access.
  • Close() error - Closes the listener and stops port renewal
  • Addr() net.Addr - Returns the NAT-aware address
  • PacketConn() net.PacketConn - Direct access to the packet connection
  • ExternalPort() int - Returns the external port number assigned by the NAT device (same as internal port in fallback mode)
  • IsFallback() bool - Returns true if NAT traversal failed and the listener is using a standard net.PacketConn without NAT hole-punching
NATAddr

Network address with NAT traversal information:

  • Network() string - Returns the network type (tcp/udp)
  • String() string - Returns the external address (same as ExternalAddr())
  • InternalAddr() string - Returns the internal network address
  • ExternalAddr() string - Returns the external network address

Note: String() returns the external address to satisfy the net.Addr interface, making NATAddr work seamlessly with code expecting standard network addresses.

NATConn

Wraps net.Conn with NAT-aware addressing:

  • LocalAddr() net.Addr - Returns NAT-aware local address
  • RemoteAddr() net.Addr - Returns remote address
  • Embeds net.Conn for all standard connection operations

How It Works

  1. Port Mapping: When creating a listener, the library attempts to create a port mapping on your router using UPnP first, then falls back to NAT-PMP
  2. External IP Discovery: Retrieves your router's external IP address
  3. Address Management: Provides both internal (LAN) and external (WAN) addresses
  4. Automatic Renewal: Continuously renews port mappings to prevent expiration
  5. Standard Interfaces: Exposes familiar Go network interfaces for easy integration

Supported Protocols

  • UPnP (Universal Plug and Play): Primary protocol for automatic port forwarding
  • NAT-PMP (NAT Port Mapping Protocol): Fallback protocol for routers that don't support UPnP

Error Handling

The library provides descriptive error messages for common failure scenarios:

  • No NAT traversal protocols available
  • Port mapping failures
  • External IP discovery issues
  • Network connectivity problems

Example error handling:

The simplest approach is to use the built-in fallback functions:

// ListenWithFallback automatically falls back to a standard listener
// if NAT traversal fails - no manual error handling needed!
listener, err := nattraversal.ListenWithFallback(8080)
if err != nil {
    log.Fatal("Failed to create listener:", err)
}
defer listener.Close()

if listener.IsFallback() {
    log.Println("Running in fallback mode (no NAT traversal)")
} else {
    log.Printf("Listening on external address: %s", listener.Addr())
}

for {
    conn, err := listener.Accept()
    if err != nil {
        log.Printf("Accept error: %v", err)
        continue
    }
    go handleConnection(conn)
}

For more control, you can handle errors manually:

listener, err := nattraversal.Listen(8080)
if err != nil {
    log.Printf("NAT traversal failed: %v", err)
    // Fall back to local-only listener
    // Note: fallbackListener is net.Listener, not *NATListener
    fallbackListener, err := net.Listen("tcp", ":8080")
    if err != nil {
        log.Fatal("All listener creation failed:", err)
    }
    // Use the fallback listener directly (it implements net.Listener)
    defer fallbackListener.Close()
    for {
        conn, err := fallbackListener.Accept()
        if err != nil {
            log.Printf("Accept error: %v", err)
            continue
        }
        go handleConnection(conn)
    }
}
// Use NAT listener normally
defer listener.Close()
for {
    conn, err := listener.Accept()
    if err != nil {
        log.Printf("Accept error: %v", err)
        continue
    }
    go handleConnection(conn)
}

Alternatively, use the net.Listener interface for unified handling:

var listener net.Listener
var err error

natListener, err := nattraversal.Listen(8080)
if err != nil {
    log.Printf("NAT traversal failed: %v, falling back to local listener", err)
    listener, err = net.Listen("tcp", ":8080")
    if err != nil {
        log.Fatal("All listener creation failed:", err)
    }
} else {
    listener = natListener
    log.Printf("Listening on external address: %s", natListener.Addr())
}
defer listener.Close()

for {
    conn, err := listener.Accept()
    if err != nil {
        log.Printf("Accept error: %v", err)
        continue
    }
    go handleConnection(conn)
}

Limitations

  • IPv4 only: This library only supports IPv4 networks. IPv6 environments are not supported due to NAT-PMP protocol limitations and gateway discovery mechanisms that rely on IPv4 addressing
  • Requires router support for UPnP or NAT-PMP protocols
  • May not work with symmetric NAT configurations
  • Firewall settings may block automatic port mapping
  • Some corporate/restricted networks disable these protocols

Dependencies

  • github.com/huin/goupnp - UPnP protocol implementation
  • github.com/jackpal/go-nat-pmp - NAT-PMP protocol implementation
  • github.com/go-i2p/logger - Structured logging

Logging

This library uses github.com/go-i2p/logger for structured logging throughout. Logging is controlled entirely via environment variables — no code changes are needed.

Environment Variables
Variable Values Description
DEBUG_I2P debug, warn, error Sets log level (default: off)
WARNFAIL_I2P any non-empty value Causes all warnings and errors to call log.Fatal (developer fast-fail mode)
Usage Examples
# Run with no logs (default)
go run main.go

# Run with debug-level logs (shows all NAT discovery steps)
DEBUG_I2P=debug go run main.go

# Run with only warnings and errors
DEBUG_I2P=warn go run main.go

# Run tests with logging enabled
DEBUG_I2P=debug go test ./...

# Developer mode: fail immediately on any warning or error
WARNFAIL_I2P=true DEBUG_I2P=debug go test ./...

License

See LICENSE file for details.

Contributing

Contributions are welcome! Please ensure that:

  • Code follows Go conventions and idioms
  • Tests are included for new functionality
  • Documentation is updated accordingly
  • Changes maintain compatibility with existing APIs

Documentation

Overview

Package nattraversal provides NAT traversal using UPnP and NAT-PMP protocols with standard Go network interfaces and automatic port renewal.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type BenchmarkHelper

type BenchmarkHelper struct {
	// contains filtered or unexported fields
}

BenchmarkHelper provides utilities for benchmarking

func NewBenchmarkHelper

func NewBenchmarkHelper() *BenchmarkHelper

NewBenchmarkHelper creates a new benchmark helper

func (*BenchmarkHelper) GetPortMapper

func (b *BenchmarkHelper) GetPortMapper() *MockPortMapper

GetPortMapper returns the port mapper for benchmarking

func (*BenchmarkHelper) SetupForBenchmark

func (b *BenchmarkHelper) SetupForBenchmark()

SetupForBenchmark configures optimal settings for benchmarking

type DirectPortMapper

type DirectPortMapper struct {
	// contains filtered or unexported fields
}

DirectPortMapper represents direct public connectivity where NAT traversal protocols are not required.

func (*DirectPortMapper) GetExternalIP

func (d *DirectPortMapper) GetExternalIP() (string, error)

GetExternalIP returns the detected directly-routable public IP.

func (*DirectPortMapper) MapPort

func (d *DirectPortMapper) MapPort(_ string, internalPort int, _ time.Duration) (int, error)

MapPort is a no-op for direct connectivity and returns the internal port unchanged.

func (*DirectPortMapper) UnmapPort

func (d *DirectPortMapper) UnmapPort(_ string, _ int) error

UnmapPort is a no-op for direct connectivity.

type MockFirewall

type MockFirewall struct {
	// contains filtered or unexported fields
}

MockFirewall simulates firewall behaviors

func NewMockFirewall

func NewMockFirewall() *MockFirewall

NewMockFirewall creates a new mock firewall

func (*MockFirewall) AllowConnection

func (f *MockFirewall) AllowConnection(ip string, port int)

AllowConnection explicitly allows a specific IP:port combination

func (*MockFirewall) BlockIP

func (f *MockFirewall) BlockIP(ip string)

BlockIP adds an IP to the blocked list

func (*MockFirewall) BlockPort

func (f *MockFirewall) BlockPort(port int)

BlockPort adds a port to the blocked list

func (*MockFirewall) IsBlocked

func (f *MockFirewall) IsBlocked(ip string, port int) bool

IsBlocked checks if a connection should be blocked

func (*MockFirewall) Reset

func (f *MockFirewall) Reset()

Reset clears all firewall rules and resets to default allow policy.

func (*MockFirewall) SetDefaultPolicy

func (f *MockFirewall) SetDefaultPolicy(allow bool)

SetDefaultPolicy sets the default firewall policy

type MockNetworkConditions

type MockNetworkConditions struct {
	PacketLoss  float64 // 0.0 to 1.0
	Latency     time.Duration
	Jitter      time.Duration
	Bandwidth   int64 // bytes per second
	Blocked     bool
	Unreachable bool
	// contains filtered or unexported fields
}

MockNetworkConditions simulates various network conditions

func NewMockNetworkConditions

func NewMockNetworkConditions() *MockNetworkConditions

NewMockNetworkConditions creates default network conditions

func (*MockNetworkConditions) SetRandomSeed

func (m *MockNetworkConditions) SetRandomSeed(seed int64)

SetRandomSeed sets a custom random seed for reproducible tests.

func (*MockNetworkConditions) SimulateLatency

func (m *MockNetworkConditions) SimulateLatency()

SimulateLatency adds simulated network latency. Uses seeded RNG for jitter calculation.

func (*MockNetworkConditions) SimulatePacketLoss

func (m *MockNetworkConditions) SimulatePacketLoss() bool

SimulatePacketLoss determines if a packet should be dropped. Uses seeded RNG for reproducible test results.

type MockPortMapper

type MockPortMapper struct {
	// contains filtered or unexported fields
}

MockPortMapper implements PortMapper interface for testing

func NewMockPortMapper

func NewMockPortMapper() *MockPortMapper

NewMockPortMapper creates a new mock port mapper

func (*MockPortMapper) ExpireMapping

func (m *MockPortMapper) ExpireMapping(protocol string, externalPort int)

ExpireMapping simulates a mapping expiring

func (*MockPortMapper) GetActiveMappings

func (m *MockPortMapper) GetActiveMappings() map[string]*PortMapping

GetActiveMappings returns all active port mappings

func (*MockPortMapper) GetExternalIP

func (m *MockPortMapper) GetExternalIP() (string, error)

GetExternalIP implements the PortMapper interface

func (*MockPortMapper) MapPort

func (m *MockPortMapper) MapPort(protocol string, internalPort int, duration time.Duration) (int, error)

MapPort implements the PortMapper interface

func (*MockPortMapper) SetExternalIP

func (m *MockPortMapper) SetExternalIP(ip string)

SetExternalIP sets the mock external IP

func (*MockPortMapper) SetFailureRate

func (m *MockPortMapper) SetFailureRate(rate float64)

SetFailureRate sets the probability of operations failing (0.0 to 1.0)

func (*MockPortMapper) SetLatency

func (m *MockPortMapper) SetLatency(d time.Duration)

SetLatency simulates network latency

func (*MockPortMapper) SetNATType

func (m *MockPortMapper) SetNATType(natType NATType)

SetNATType sets the NAT behavior type

func (*MockPortMapper) SetPortExhaustion

func (m *MockPortMapper) SetPortExhaustion(exhausted bool)

SetPortExhaustion simulates port exhaustion scenarios

func (*MockPortMapper) SetProtocolSupport

func (m *MockPortMapper) SetProtocolSupport(upnp, natpmp bool)

SetProtocolSupport configures which protocols are supported

func (*MockPortMapper) SetRandomSeed

func (m *MockPortMapper) SetRandomSeed(seed int64)

SetRandomSeed sets a custom random seed for reproducible tests. Use different seeds to test different random scenarios deterministically.

func (*MockPortMapper) SimulateMappingChange

func (m *MockPortMapper) SimulateMappingChange(protocol string, oldPort, newPort int)

SimulateMappingChange simulates NAT mapping changes mid-connection

func (*MockPortMapper) UnmapPort

func (m *MockPortMapper) UnmapPort(protocol string, externalPort int) error

UnmapPort implements the PortMapper interface

type MockRenewalManager

type MockRenewalManager struct {
	// contains filtered or unexported fields
}

MockRenewalManager provides a testable renewal manager

func NewMockRenewalManager

func NewMockRenewalManager() *MockRenewalManager

NewMockRenewalManager creates a new mock renewal manager

func (*MockRenewalManager) GetFailureCount

func (m *MockRenewalManager) GetFailureCount() int

GetFailureCount returns the number of failed renewals

func (*MockRenewalManager) GetRenewalCount

func (m *MockRenewalManager) GetRenewalCount() int

GetRenewalCount returns the number of successful renewals

func (*MockRenewalManager) IsStopped

func (m *MockRenewalManager) IsStopped() bool

IsStopped returns whether the renewal manager has been stopped

func (*MockRenewalManager) SetShouldFail

func (m *MockRenewalManager) SetShouldFail(fail bool)

SetShouldFail configures renewal failures

type MockUDPConn

type MockUDPConn struct {
	// contains filtered or unexported fields
}

MockUDPConn provides a mock UDP connection for testing

func NewMockUDPConn

func NewMockUDPConn(localAddr, remoteAddr *net.UDPAddr) *MockUDPConn

NewMockUDPConn creates a new mock UDP connection

func (*MockUDPConn) AddReadData

func (c *MockUDPConn) AddReadData(data []byte)

AddReadData adds data to the read buffer

func (*MockUDPConn) Close

func (c *MockUDPConn) Close() error

Close implements net.Conn interface

func (*MockUDPConn) GetWrittenData

func (c *MockUDPConn) GetWrittenData() [][]byte

GetWrittenData returns all written data

func (*MockUDPConn) LocalAddr

func (c *MockUDPConn) LocalAddr() net.Addr

LocalAddr implements net.Conn interface

func (*MockUDPConn) Read

func (c *MockUDPConn) Read(b []byte) (n int, err error)

Read implements net.Conn interface

func (*MockUDPConn) ReadFrom

func (c *MockUDPConn) ReadFrom(p []byte) (n int, addr net.Addr, err error)

ReadFrom implements net.PacketConn interface

func (*MockUDPConn) RemoteAddr

func (c *MockUDPConn) RemoteAddr() net.Addr

RemoteAddr implements net.Conn interface

func (*MockUDPConn) SetDeadline

func (c *MockUDPConn) SetDeadline(t time.Time) error

SetDeadline implements net.Conn interface

func (*MockUDPConn) SetFirewall

func (c *MockUDPConn) SetFirewall(firewall *MockFirewall)

SetFirewall sets the firewall for this connection

func (*MockUDPConn) SetNetworkConditions

func (c *MockUDPConn) SetNetworkConditions(conditions *MockNetworkConditions)

SetNetworkConditions sets the network conditions for this connection

func (*MockUDPConn) SetReadDeadline

func (c *MockUDPConn) SetReadDeadline(t time.Time) error

SetReadDeadline implements net.Conn interface

func (*MockUDPConn) SetWriteDeadline

func (c *MockUDPConn) SetWriteDeadline(t time.Time) error

SetWriteDeadline implements net.Conn interface

func (*MockUDPConn) Write

func (c *MockUDPConn) Write(b []byte) (n int, err error)

Write implements net.Conn interface

func (*MockUDPConn) WriteTo

func (c *MockUDPConn) WriteTo(p []byte, addr net.Addr) (n int, err error)

WriteTo implements net.PacketConn interface

type NATAddr

type NATAddr struct {
	// contains filtered or unexported fields
}

NATAddr represents a network address with NAT traversal information. Moved from: addr.go

func NewNATAddr

func NewNATAddr(network, internalAddr, externalAddr string) *NATAddr

NewNATAddr creates a new NATAddr with internal and external addresses.

func (*NATAddr) ExternalAddr

func (a *NATAddr) ExternalAddr() string

ExternalAddr returns the external network address.

func (*NATAddr) InternalAddr

func (a *NATAddr) InternalAddr() string

InternalAddr returns the internal network address.

func (*NATAddr) Network

func (a *NATAddr) Network() string

Network returns the network type (tcp/udp).

func (*NATAddr) String

func (a *NATAddr) String() string

String returns the external address for external connections.

type NATConn

type NATConn struct {
	net.Conn
	// contains filtered or unexported fields
}

NATConn wraps a net.Conn with NAT-aware addressing. Moved from: conn.go

func (*NATConn) LocalAddr

func (c *NATConn) LocalAddr() net.Addr

LocalAddr returns the local network address with NAT info.

func (*NATConn) RemoteAddr

func (c *NATConn) RemoteAddr() net.Addr

RemoteAddr returns the remote network address.

type NATListener

type NATListener struct {
	// contains filtered or unexported fields
}

NATListener implements net.Listener with automatic NAT traversal. Moved from: listener.go

func Listen

func Listen(port int) (*NATListener, error)

Listen creates a TCP listener with NAT traversal on the specified port. This is a convenience wrapper around ListenContext using context.Background().

func ListenContext

func ListenContext(ctx context.Context, port int) (*NATListener, error)

ListenContext creates a TCP listener with NAT traversal on the specified port. The context can be used to cancel the discovery and mapping operations. Once the listener is created, the context is no longer used - use Close() to stop the listener.

func ListenWithFallback

func ListenWithFallback(port int) (*NATListener, error)

ListenWithFallback creates a TCP listener with NAT traversal on the specified port. If NAT traversal fails (UPnP and NAT-PMP both unavailable), it falls back to a standard net.Listener without NAT hole-punching. This is a convenience wrapper around ListenWithFallbackContext using context.Background().

func ListenWithFallbackContext

func ListenWithFallbackContext(ctx context.Context, port int) (*NATListener, error)

ListenWithFallbackContext creates a TCP listener with NAT traversal on the specified port. If NAT traversal fails (UPnP and NAT-PMP both unavailable), it falls back to a standard net.Listener without NAT hole-punching. The context can be used to cancel the discovery and mapping operations. Once the listener is created, the context is no longer used - use Close() to stop the listener.

When fallback is used:

  • ExternalPort() returns the same as the internal port
  • Addr() returns a NATAddr where internal and external addresses are the same
  • No port renewal is performed (the renewal manager is nil)
  • IsFallback() returns true

func (*NATListener) Accept

func (l *NATListener) Accept() (net.Conn, error)

Accept waits for and returns the next connection to the listener.

func (*NATListener) Addr

func (l *NATListener) Addr() net.Addr

Addr returns the listener's network address.

func (*NATListener) Close

func (l *NATListener) Close() error

Close closes the listener and stops port renewal.

func (*NATListener) ExternalPort

func (l *NATListener) ExternalPort() int

ExternalPort returns the external port number assigned by the NAT device. This value may change if the NAT device assigns a different port during renewal. In fallback mode, this returns the same as the internal port.

func (*NATListener) IsFallback

func (l *NATListener) IsFallback() bool

IsFallback returns true if NAT traversal failed and the listener is using a standard net.Listener without NAT hole-punching.

type NATPMPMapper

type NATPMPMapper struct {
	// contains filtered or unexported fields
}

NATPMPMapper implements PortMapper using NAT-PMP protocol. Moved from: addr.go

func NewNATPMPMapper

func NewNATPMPMapper() (*NATPMPMapper, error)

NewNATPMPMapper discovers and creates a NAT-PMP mapper.

func (*NATPMPMapper) GetExternalIP

func (n *NATPMPMapper) GetExternalIP() (string, error)

GetExternalIP returns the external IP address via NAT-PMP.

func (*NATPMPMapper) MapPort

func (n *NATPMPMapper) MapPort(protocol string, internalPort int, duration time.Duration) (int, error)

MapPort creates a port mapping via NAT-PMP.

func (*NATPMPMapper) UnmapPort

func (n *NATPMPMapper) UnmapPort(protocol string, externalPort int) error

UnmapPort removes a port mapping via NAT-PMP.

type NATPacketConn

type NATPacketConn struct {
	net.PacketConn
	// contains filtered or unexported fields
}

NATPacketConn wraps a net.PacketConn with NAT-aware addressing. It coordinates with NATPacketListener to ensure Close() is idempotent and safe to call from either the connection or the listener.

func (*NATPacketConn) Close

func (c *NATPacketConn) Close() error

Close closes the connection. This method is idempotent - calling it multiple times is safe and will only close the underlying connection once, returning the same error.

func (*NATPacketConn) LocalAddr

func (c *NATPacketConn) LocalAddr() net.Addr

LocalAddr returns the local network address with NAT info.

func (*NATPacketConn) ReadFrom

func (c *NATPacketConn) ReadFrom(p []byte) (n int, addr net.Addr, err error)

ReadFrom reads a packet from the connection.

func (*NATPacketConn) SetDeadline

func (c *NATPacketConn) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines.

func (*NATPacketConn) SetReadDeadline

func (c *NATPacketConn) SetReadDeadline(t time.Time) error

SetReadDeadline sets the deadline for future ReadFrom calls.

func (*NATPacketConn) SetWriteDeadline

func (c *NATPacketConn) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the deadline for future WriteTo calls.

func (*NATPacketConn) WriteTo

func (c *NATPacketConn) WriteTo(p []byte, addr net.Addr) (n int, err error)

WriteTo writes a packet to the connection.

type NATPacketListener

type NATPacketListener struct {
	// contains filtered or unexported fields
}

NATPacketListener implements a packet listener with NAT traversal. Moved from: packetlistener.go

func ListenPacket

func ListenPacket(port int) (*NATPacketListener, error)

ListenPacket creates a UDP packet listener with NAT traversal on the specified port. This is a convenience wrapper around ListenPacketContext using context.Background().

func ListenPacketContext

func ListenPacketContext(ctx context.Context, port int) (*NATPacketListener, error)

ListenPacketContext creates a UDP packet listener with NAT traversal on the specified port. The context can be used to cancel the discovery and mapping operations. Once the listener is created, the context is no longer used - use Close() to stop the listener.

func ListenPacketWithFallback

func ListenPacketWithFallback(port int) (*NATPacketListener, error)

ListenPacketWithFallback creates a UDP packet listener with NAT traversal on the specified port. If NAT traversal fails (UPnP and NAT-PMP both unavailable), it falls back to a standard net.PacketConn without NAT hole-punching. This is a convenience wrapper around ListenPacketWithFallbackContext using context.Background().

func ListenPacketWithFallbackContext

func ListenPacketWithFallbackContext(ctx context.Context, port int) (*NATPacketListener, error)

ListenPacketWithFallbackContext creates a UDP packet listener with NAT traversal on the specified port. If NAT traversal fails (UPnP and NAT-PMP both unavailable), it falls back to a standard net.PacketConn without NAT hole-punching. The context can be used to cancel the discovery and mapping operations. Once the listener is created, the context is no longer used - use Close() to stop the listener.

When fallback is used:

  • ExternalPort() returns the same as the internal port
  • Addr() returns a NATAddr where internal and external addresses are the same
  • No port renewal is performed (the renewal manager is nil)
  • IsFallback() returns true

func (*NATPacketListener) Accept

func (l *NATPacketListener) Accept() (net.PacketConn, error)

Accept returns a packet connection (satisfies a hypothetical net.PacketListener interface). Note: For UDP, this returns the same cached connection each time since UDP is connectionless. Unlike TCP's Accept which blocks waiting for new connections, this immediately returns the single packet connection associated with this listener.

func (*NATPacketListener) Addr

func (l *NATPacketListener) Addr() net.Addr

Addr returns the listener's network address.

func (*NATPacketListener) Close

func (l *NATPacketListener) Close() error

Close closes the packet listener and stops port renewal. This method is idempotent - calling it multiple times is safe. It coordinates with NATPacketConn.Close() to ensure the underlying connection is only closed once, even if both are called.

func (*NATPacketListener) ExternalPort

func (l *NATPacketListener) ExternalPort() int

ExternalPort returns the external port number assigned by the NAT device. This value may change if the NAT device assigns a different port during renewal. In fallback mode, this returns the same as the internal port.

func (*NATPacketListener) IsFallback

func (l *NATPacketListener) IsFallback() bool

IsFallback returns true if NAT traversal failed and the listener is using a standard net.PacketConn without NAT hole-punching.

func (*NATPacketListener) PacketConn

func (l *NATPacketListener) PacketConn() net.PacketConn

PacketConn returns the underlying packet connection. Returns the same cached instance on each call.

type NATType

type NATType int

NATType represents different NAT behaviors

const (
	FullConeNAT NATType = iota
	RestrictedNAT
	PortRestrictedNAT
	SymmetricNAT
)

type PortChangeCallback

type PortChangeCallback func(newExternalPort int)

PortChangeCallback is called when the external port changes during renewal. The callback receives the new external port number.

type PortMapper

type PortMapper interface {
	MapPort(protocol string, internalPort int, duration time.Duration) (externalPort int, err error)
	UnmapPort(protocol string, externalPort int) error
	GetExternalIP() (string, error)
}

PortMapper defines the interface for NAT traversal protocols.

func NewPortMapper

func NewPortMapper() (PortMapper, error)

NewPortMapper creates a port mapper, trying direct connectivity first, then UPnP, then NAT-PMP. This is a convenience wrapper around NewPortMapperContext using context.Background().

func NewPortMapperContext

func NewPortMapperContext(ctx context.Context) (PortMapper, error)

NewPortMapperContext creates a port mapper with context support, trying direct connectivity first, then UPnP, then NAT-PMP. The context is passed through to the discovery process, allowing cancellation during slow network operations.

type PortMapping

type PortMapping struct {
	Protocol     string
	InternalPort int
	ExternalPort int
	ExpiresAt    time.Time
	Active       bool
}

PortMapping represents a mock port mapping

type RenewalManager

type RenewalManager struct {
	// contains filtered or unexported fields
}

RenewalManager handles automatic port mapping renewal. Moved from: renew.go

func NewRenewalManager

func NewRenewalManager(mapper PortMapper, protocol string, internalPort, externalPort int) *RenewalManager

NewRenewalManager creates a renewal manager for a port mapping.

func (*RenewalManager) ExternalPort

func (r *RenewalManager) ExternalPort() int

ExternalPort returns the current external port number. This may change if the NAT device assigns a different port during renewal.

func (*RenewalManager) SetPortChangeCallback

func (r *RenewalManager) SetPortChangeCallback(callback PortChangeCallback)

SetPortChangeCallback sets a callback function that will be invoked when the external port changes during renewal. This can happen if the NAT device assigns a different port during renewal (rare but possible).

func (*RenewalManager) Start

func (r *RenewalManager) Start()

Start begins the renewal process in a background goroutine. Multiple Start/Stop cycles are safe - each cycle creates fresh channels and the goroutine captures local references to avoid data races.

func (*RenewalManager) Stop

func (r *RenewalManager) Stop()

Stop terminates the renewal process and unmaps the port.

type TestHelper

type TestHelper struct {
	// contains filtered or unexported fields
}

TestHelper provides utilities for NAT traversal testing

func NewTestHelper

func NewTestHelper(t *testing.T) *TestHelper

NewTestHelper creates a new test helper instance

func (*TestHelper) AssertEqual

func (h *TestHelper) AssertEqual(expected, actual interface{}, message string)

AssertEqual fails the test if values are not equal

func (*TestHelper) AssertError

func (h *TestHelper) AssertError(err error, message string)

AssertError fails the test if error is nil

func (*TestHelper) AssertNoError

func (h *TestHelper) AssertNoError(err error, message string)

AssertNoError fails the test if error is not nil

func (*TestHelper) AssertNotEqual

func (h *TestHelper) AssertNotEqual(expected, actual interface{}, message string)

AssertNotEqual fails the test if values are equal

func (*TestHelper) AssertPortMappingExists

func (h *TestHelper) AssertPortMappingExists(protocol string, externalPort int, message string)

AssertPortMappingExists verifies a port mapping exists

func (*TestHelper) AssertPortMappingNotExists

func (h *TestHelper) AssertPortMappingNotExists(protocol string, externalPort int, message string)

AssertPortMappingNotExists verifies a port mapping does not exist

func (*TestHelper) Cleanup

func (h *TestHelper) Cleanup()

Cleanup cleans up all resources created during testing

func (*TestHelper) CreateMockConnection

func (h *TestHelper) CreateMockConnection(localPort, remotePort int) *MockUDPConn

CreateMockConnection creates a mock UDP connection with configured conditions

func (*TestHelper) CreatePortMapping

func (h *TestHelper) CreatePortMapping(protocol string, internalPort int, duration time.Duration) (int, error)

CreatePortMapping creates a port mapping and tracks it for cleanup

func (*TestHelper) CreateRenewalManager

func (h *TestHelper) CreateRenewalManager(protocol string, internalPort, externalPort int) *RenewalManager

CreateRenewalManager creates a renewal manager and tracks it for cleanup

func (*TestHelper) GetFirewall

func (h *TestHelper) GetFirewall() *MockFirewall

GetFirewall returns the mock firewall for configuration

func (*TestHelper) GetNetworkConditions

func (h *TestHelper) GetNetworkConditions() *MockNetworkConditions

GetNetworkConditions returns the mock network conditions for configuration

func (*TestHelper) GetPortMapper

func (h *TestHelper) GetPortMapper() *MockPortMapper

GetPortMapper returns the mock port mapper for advanced operations

func (*TestHelper) Reset

func (h *TestHelper) Reset()

Reset resets the TestHelper state between subtests to prevent state leakage. This should be called at the start of each subtest when using a shared TestHelper.

func (*TestHelper) RunScenarios

func (h *TestHelper) RunScenarios(scenarios []TestScenario, testFunc func(*TestHelper, TestScenario))

RunScenarios runs multiple test scenarios

func (*TestHelper) RunWithCleanup

func (h *TestHelper) RunWithCleanup(testFunc func())

RunWithCleanup runs a test function and ensures cleanup happens

func (*TestHelper) SetupFullConeNAT

func (h *TestHelper) SetupFullConeNAT()

SetupFullConeNAT configures the environment for Full Cone NAT testing

func (*TestHelper) SetupPoorNetwork

func (h *TestHelper) SetupPoorNetwork()

SetupPoorNetwork simulates poor network conditions

func (*TestHelper) SetupRestrictedNAT

func (h *TestHelper) SetupRestrictedNAT()

SetupRestrictedNAT configures the environment for Restricted NAT testing

func (*TestHelper) SetupRestrictiveFirewall

func (h *TestHelper) SetupRestrictiveFirewall()

SetupRestrictiveFirewall configures a restrictive firewall

func (*TestHelper) SetupSymmetricNAT

func (h *TestHelper) SetupSymmetricNAT()

SetupSymmetricNAT configures the environment for Symmetric NAT testing

func (*TestHelper) SimulateNetworkFailure

func (h *TestHelper) SimulateNetworkFailure() func()

SimulateNetworkFailure temporarily increases failure rates

func (*TestHelper) SimulatePortExhaustion

func (h *TestHelper) SimulatePortExhaustion() func()

SimulatePortExhaustion enables port exhaustion simulation

func (*TestHelper) VerifyMapping

func (h *TestHelper) VerifyMapping(protocol string, externalPort int) bool

VerifyMapping checks if a port mapping exists and is active

func (*TestHelper) WaitForRenewal

func (h *TestHelper) WaitForRenewal()

WaitForRenewal waits for at least one renewal cycle to complete

type TestScenario

type TestScenario struct {
	Name        string
	NATType     NATType
	HasFirewall bool
	PoorNetwork bool
	FailureRate float64
	Expected    bool
}

TestScenario represents a test scenario configuration

type UPnPMapper

type UPnPMapper struct {
	// contains filtered or unexported fields
}

UPnPMapper implements PortMapper using UPnP IGD protocol. Supports WANIPConnection1, WANIPConnection2, and WANPPPConnection1 services.

func NewUPnPMapper

func NewUPnPMapper() (*UPnPMapper, error)

NewUPnPMapper discovers and creates a UPnP mapper. This is a convenience wrapper around NewUPnPMapperContext using context.Background().

func NewUPnPMapperContext

func NewUPnPMapperContext(ctx context.Context) (*UPnPMapper, error)

NewUPnPMapperContext discovers and creates a UPnP mapper with context support. The context allows cancellation of the discovery process, which can take several seconds. It attempts discovery in order of preference: WANIPConnection2, WANIPConnection1, then WANPPPConnection1, using the first service that responds with available devices.

func (*UPnPMapper) GetExternalIP

func (u *UPnPMapper) GetExternalIP() (string, error)

GetExternalIP returns the external IP address via UPnP.

func (*UPnPMapper) MapPort

func (u *UPnPMapper) MapPort(protocol string, internalPort int, duration time.Duration) (int, error)

MapPort creates a port mapping via UPnP.

func (*UPnPMapper) UnmapPort

func (u *UPnPMapper) UnmapPort(protocol string, externalPort int) error

UnmapPort removes a port mapping via UPnP.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL