netutil

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: Apache-2.0 Imports: 16 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrBlocked = errors.New("request blocked")

Functions

func AddrInCIDR

func AddrInCIDR(cidr string, n int) (string, error)

func CloseConns

func CloseConns(closers ...io.Closer)

CloseConns safely closes one or more io.Closer (like net.Conn). It is nil-safe and intentionally ignores errors from Close(), which is a common pattern in defer statements where handling the error is not feasible or desired.

func DescribeRoute

func DescribeRoute(src, dst net.Conn) string

func DialFastest

func DialFastest(
	ctx context.Context,
	dst *Destination,
	network string,
	timeout time.Duration,
	bindFunc BindFunc,
) (net.Conn, error)

DialFastest attempts robust connections to the server and returns the first successful conn. All the other connections will be automatically canceled by calling `cancel()` timeout is applied per-dial as a deadline; pass 0 to disable. If bindFunc is not nil, it is called to configure the dialer before each dial attempt.

func DiscoverInterface added in v1.5.6

func DiscoverInterface() (*net.Interface, net.IP, error)

DiscoverInterface discovers the interface of the default route and its local IP from the OS. It does not require a gateway.

func FindSafeCIDR

func FindSafeCIDR() (string, error)

func GetRxBytes

func GetRxBytes() uint64

func GetTxBytes

func GetTxBytes() uint64

func IsConnectionResetByPeer

func IsConnectionResetByPeer(err error) bool

func SetTTL

func SetTTL(conn net.Conn, isIPv4 bool, ttl uint8) error

SetTTL configures the TTL or Hop Limit depending on the IP version. The isIPv4 parameter is determined by examining the remote address of the connection.

func TunnelConns

func TunnelConns(
	ctx context.Context,
	resCh chan<- TransferResult,
	src net.Conn,
	dst net.Conn,
	dir TunnelDirType,
)

TunnelConns copies data from src to dst. It sends the result to resCh upon completion. It filters out benign errors like EOF, pipe closed, or read timeouts (for UDP).

func WaitForTunnelCompletion

func WaitForTunnelCompletion(
	ctx context.Context,
	logger zerolog.Logger,
	resCh <-chan TransferResult,
	startedAt time.Time,
	route string,
	errHandler func(errs []error) error,
) error

WaitForTunnelCompletion aggregates results and logs the summary. errHandler processes the list of errors to determine the final error.

Types

type BindFunc

type BindFunc func(dialer *net.Dialer, network string, targetIP net.IP) error

BindFunc is called to configure the dialer before dialing. If it returns an error, the dial attempt fails.

type BufferedConn

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

BufferedConn wraps a net.Conn with a bufio.Reader to support peeking.

func NewBufferedConn

func NewBufferedConn(c net.Conn) *BufferedConn

func (*BufferedConn) Peek

func (b *BufferedConn) Peek(n int) ([]byte, error)

func (*BufferedConn) Read

func (b *BufferedConn) Read(p []byte) (int, error)

type ConnRegistry

type ConnRegistry[K cache.Key] struct {
	// contains filtered or unexported fields
}

ConnRegistry manages UDP connections with LRU eviction policy and idle timeout.

func NewConnRegistry

func NewConnRegistry[K cache.Key](
	capacity int,
	timeout time.Duration,
) *ConnRegistry[K]

NewConnRegistry creates a new pool with the specified capacity and timeout.

func (*ConnRegistry[K]) CloseAll

func (p *ConnRegistry[K]) CloseAll()

CloseAll closes all connections in the pool.

func (*ConnRegistry[K]) Evict

func (p *ConnRegistry[K]) Evict(key K)

Evict closes and removes the connection from the pool.

func (*ConnRegistry[K]) Fetch

func (p *ConnRegistry[K]) Fetch(key K) (*IdleTimeoutConn, bool)

Fetch retrieves a connection from the pool, refreshing its LRU status.

func (*ConnRegistry[K]) Has

func (p *ConnRegistry[K]) Has(key K) bool

Has checks if the connection exists in the cache.

func (*ConnRegistry[K]) RunCleanupLoop

func (p *ConnRegistry[K]) RunCleanupLoop(appctx context.Context)

RunCleanupLoop runs the background cleanup goroutine. It exits when appctx is cancelled, closing all remaining cached connections.

func (*ConnRegistry[K]) Size

func (p *ConnRegistry[K]) Size() int

Size returns the number of connections in the pool.

func (*ConnRegistry[K]) Store

func (p *ConnRegistry[K]) Store(key K, rawConn net.Conn) *IdleTimeoutConn

Store adds a connection to the cache and returns the wrapped connection. If capacity is full, evicts the least recently used connection.

type Destination

type Destination struct {
	Host  string
	Addrs []net.IP
	Port  int
}

Destination identifies *where* to dial — domain name, candidate IPs, and port. Per-dial concerns (timeout, bind hook, etc.) are passed to DialFastest separately so a Destination value can be reused across rule lookups without carrying stale settings.

func (*Destination) IsValid

func (d *Destination) IsValid(listenAddr *net.TCPAddr) (bool, error)

func (*Destination) String

func (d *Destination) String() string

type IPKey

type IPKey [16]byte

IPKey represents an IP address for zero-allocation cache mapping

func NewIPKey

func NewIPKey(ip net.IP) IPKey

NewIPKey zero-alloc constructs an IPKey from net.IP

func (IPKey) Bytes added in v1.5.2

func (k IPKey) Bytes() []byte

func (IPKey) String

func (k IPKey) String() string

String returns the string representation of the IPKey.

type IdleTimeoutConn

type IdleTimeoutConn struct {
	net.Conn
	Key     any
	Timeout time.Duration
	// contains filtered or unexported fields
}

IdleTimeoutConn wraps a net.Conn to extend the deadline on every Read/Write call. This is useful for sessions which should stay alive as long as there is activity.

func NewIdleTimeoutConn

func NewIdleTimeoutConn(conn net.Conn, timeout time.Duration) *IdleTimeoutConn

NewIdleTimeoutConn wraps a net.Conn and securely initializes its internal atomic deadlines.

func (*IdleTimeoutConn) Close

func (c *IdleTimeoutConn) Close() error

func (*IdleTimeoutConn) ExtendDeadline

func (c *IdleTimeoutConn) ExtendDeadline() bool

ExtendDeadline attempts to extend the connection's deadline. Returns false if the connection was already expired.

func (*IdleTimeoutConn) IsExpired

func (c *IdleTimeoutConn) IsExpired(now time.Time) bool

IsExpired safely checks if the connection has surpassed its calculated expiration time.

func (*IdleTimeoutConn) Read

func (c *IdleTimeoutConn) Read(b []byte) (int, error)

func (*IdleTimeoutConn) Write

func (c *IdleTimeoutConn) Write(b []byte) (int, error)

type NATKey

type NATKey struct {
	SrcIP   [16]byte
	SrcPort uint16
	DstIP   [16]byte
	DstPort uint16
}

NATKey represents a 4-tuple (SrcIP, SrcPort, DstIP, DstPort) for zero-allocation NAT session mapping

func NewNATKey

func NewNATKey(srcIP net.IP, srcPort int, dstIP net.IP, dstPort int) NATKey

NewNATKey zero-alloc constructs a NATKey from two UDPAddr

func (NATKey) Bytes added in v1.5.2

func (k NATKey) Bytes() []byte

func (NATKey) String

func (k NATKey) String() string

String returns the string representation of the session key. Only used for debugging / logging.

type Route

type Route struct {
	Iface   net.Interface
	LocalIP net.IP
	Gateway net.IP
}

Route represents the default network route.

func DiscoverRoute added in v1.5.6

func DiscoverRoute(gateway net.IP) (*Route, error)

DiscoverRoute discovers the default network route. If gateway is nil, the gateway IP and interface are resolved from the OS routing table. Otherwise the given gateway is used as is, and the interface is the one whose subnet contains it, so the two always match.

type TrackingConn

type TrackingConn struct {
	net.Conn
}

func (*TrackingConn) Read

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

func (*TrackingConn) Write

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

type TransferResult

type TransferResult struct {
	Written int64
	Dir     TunnelDirType
	Err     error
}

TransferResult holds the result of a unidirectional tunnel transfer.

type TunnelDirType

type TunnelDirType int
const (
	TunnelDirOut TunnelDirType = iota
	TunnelDirIn
)

Jump to

Keyboard shortcuts

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