gonnect

package module
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: May 22, 2026 License: CC0-1.0 Imports: 19 Imported by: 0

README

Go Reference

Gonnect

Gonnect is a collection of network helper functions and common types that have been reinvented and reimplemented countless times in many Go projects. I created it mostly for myself, but feel free to use it in your projects or suggest features.

There are some projects based on Gonnect or created for similar use cases. You may find them useful too:

  • gonnect-netstack - gVisor's netstack integration for the gonnect ecosystem
  • gonnect-vpn-example - An example of simple point-to-point VPN built on top of the gonnect ecosystem
  • tuntap - Cross-platform TUN device library extracted from wireguard-go
  • ygg - alternative yggdrasil mesh network implementation with WASM builds supported
  • wgo - WireGuard library based on gonnect-netstack, tuntap, batchudp with amnesia obfuscation support
  • wg-web-demo - browser WASM demonstration of HTTP over WireGuard over socks-over-websocket using userspace TCP/IP stack
  • socksgo - The most complete, compatible, feature-rich, and extensible SOCKS library for Go
  • mnlib - mesh-oriented DNS names lib
  • batchudp - UDP transport package extracted from wireguard-go/conn
  • bufpool - Byte buffer pool interface and testing helpers
  • putback - A minimal library that provides wrappers for common I/O interfaces, adding the ability to return read bytes back to the stream for subsequent reading
  • mnlib - Mesh-oriented DNS names lib (.meshname, .meship, .ygg, .pk.ygg)

License

Files in this repository are distributed under the CC0 license.

CC0
To the extent possible under law, ASCIIMoth has waived all copyright and related or neighboring rights to gonnect.

Documentation

Overview

Package gonnect provides network helper functions and common network types. NativeConfig builds a NativeNetwork backed by Go's standard net package. NativeNetwork implements Network only; wrap it with DetachNetwork when independent Up, Down, or Close state is required.

DetachNetwork wraps a Network with independent Up, Down, and Close state. Stopping the wrapper does not stop the wrapped Network, but it cancels wrapper operations that honor context cancellation and closes connections, listeners, packet connections, and accepted connections created through that wrapper. Multiple detached network wrappers can be used over the same Network independently.

Index

Constants

View Source
const (
	// RouterSlots is the number of backend slots available in a Router.
	RouterSlots = 16
)

Variables

View Source
var ErrNetworkDown = &net.OpError{
	Op:  "network",
	Net: "down",
	Err: errors.New("network is down"),
}
View Source
var (
	ErrNoDefaultInterface = errors.New("failed to found default interface")
)
View Source
var ErrUnsupported = errors.New("unsupported")

Functions

func AddrsEq added in v0.13.0

func AddrsEq(a, b net.Addr) bool

AddrsEq reports whether a and b are equal addresses (same host and port). It compares IP addresses and ports for TCP/UDP addr types, or string representation for other types.

func AddrsSameHost added in v0.13.0

func AddrsSameHost(a, b net.Addr) bool

AddrsSameHost reports whether a and b represent addresses on the same host. It compares IP addresses for TCP/UDP addr types, or host strings for other types. Port numbers are ignored in the comparison.

func CheckURLBoolKey added in v0.13.0

func CheckURLBoolKey(values map[string][]string, key string) (f bool, s bool)

CheckURLBoolKey checks if a key exists in a URL values map and interprets its value as a boolean. It returns two booleans: f is true if the key exists with a truthy value, s is true if the key exists at all. Truthy values include: "true", "yes", "ok", "1", or an empty string.

func CloseAll added in v0.13.0

func CloseAll(closers []io.Closer)

func ClosedNetworkErrToNil added in v0.13.0

func ClosedNetworkErrToNil(err error) error

ClosedNetworkErrToNil returns nil if err represents a closed network connection error. It unwraps err to find the root cause and checks for common closed connection messages. Returns the original error if it is not a closed connection error.

func ConnClosed added in v0.13.0

func ConnClosed(op, network string, src, addr net.Addr) net.Error

ConnClosed returns a net.Error representing an operation on a closed network connection. The op parameter is the operation being performed (e.g. "read", "write"). The network parameter is the network type (e.g. "tcp", "udp"). src and addr represent the source and destination addresses of the connection.

func ConnRefused added in v0.13.0

func ConnRefused(n, a string) error

ConnRefused returns an error representing a connection refusal. The n parameter is the network type (e.g. "tcp", "udp"). The a parameter is the address that refused the connection.

func ConnWithCallbacks

func ConnWithCallbacks(c net.Conn, cb *Callbacks) net.Conn

ConnWithCallbacks wraps a net.Conn with callbacks, using the most specific wrapper type based on the underlying connection type.

func CopyPacket added in v0.13.0

func CopyPacket(
	dst, src net.PacketConn,
	bufSize int,
	pool bufpool.Pool,
) (written int64, err error)

CopyPacket copies packets from src to dst, preserving packet boundaries. It reads individual datagrams from src and writes them to dst. bufSize specifies the buffer size to use, and pool is used for buffer allocation.

func DnsReqErr added in v0.13.0

func DnsReqErr(host, srv string) error

DnsReqErr returns a net.DNSError representing a DNS request failure. The host parameter is the hostname that was looked up (e.g. example.com). The srv parameter is the DNS server address (e.g. 8.8.8.8:53).

func Drain added in v0.13.0

func Drain[T any](c <-chan T)

Drain reads all elements from c while there are some. It doesnt. Close channel.

func FalseFilter

func FalseFilter(_, _ string) bool

FalseFilter is a Filter that always returns false.

func FamilyFromNetwork added in v0.13.0

func FamilyFromNetwork(network string) string

FamilyFromNetwork returns the IP family ("ip", "ip4", or "ip6") for a given network string. For example, "tcp", "udp", or "ip" all return "ip", while "tcp4", "udp4", "ip4" return "ip4".

func File added in v0.13.0

func File(a any) (f *os.File, err error)

File returns the underlying *os.File from a connection. It checks if the value implements the withFile interface, or unwraps the value to find one that does. Returns nil if the value is nil or doesn't implement the interface.

func GetWrapped

func GetWrapped(obj any) any

GetWrapped extracts the wrapped value from an object. If obj is nil or does not implement Wrapper, returns nil.

func IpEqual added in v0.13.0

func IpEqual(a, b net.IP) bool

IpEqual reports whether a and b are equal IP addresses. Nil IPs are considered equal to each other, and not equal to non-nil IPs.

func IsIPNetwork added in v0.13.0

func IsIPNetwork(network string) bool

IsIPNetwork reports whether network is an IP-based network (ip, ip4, or ip6).

func IsLocal added in v0.13.0

func IsLocal(addr string) bool

IsLocal reports whether addr is a local address ("localhost" or a loopback IP). It returns true for "localhost", "127.0.0.1", "::1", or any IP in the 127.0.0.0/8 range.

func IsTCPNetwork added in v0.13.0

func IsTCPNetwork(network string) bool

IsTCPNetwork reports whether network is a TCP-based network (tcp, tcp4, or tcp6).

func IsUDPNetwork added in v0.13.0

func IsUDPNetwork(network string) bool

IsUDPNetwork reports whether network is a UDP-based network (udp, udp4, or udp6).

func JointIPPort added in v0.13.0

func JointIPPort(ip net.IP, port int) string

JointIPPort joins an IP address and port into a host:port string.

func ListenDeniedErr added in v0.13.0

func ListenDeniedErr(n, a string) error

ListenDeniedErr returns an error representing a permission denied when attempting to listen on an address. The n parameter is the network type (e.g. "tcp", "udp"). The a parameter is the address that denied the listen attempt.

func ListenerWithCallbacks

func ListenerWithCallbacks(l net.Listener, cb *Callbacks) net.Listener

ListenerWithCallbacks wraps a net.Listener with callbacks, using the most specific wrapper type based on the underlying listener type.

func LookupPortOffline

func LookupPortOffline(network, service string) (port int, err error)

LookupPortOffline resolve port name to port (e.g. http to 80) using only local data.

func LoopbackFilter

func LoopbackFilter(_, address string) bool

LoopbackFilter returns true for localhost and loopback addresses.

func MultipathTCP added in v0.13.0

func MultipathTCP(c net.Conn) (bool, error)

MultipathTCP reports whether the connection uses Multipath TCP (MPTCP). It checks if the connection implements the withMultipathTCP interface, or unwraps the connection to find one that does.

func NetPacketConnWithCallbacks

func NetPacketConnWithCallbacks(
	c net.PacketConn,
	cb *Callbacks,
) net.PacketConn

NetPacketConnWithCallbacks wraps a net.PacketConn with callbacks, using the most specific wrapper type based on the underlying connection type.

func NetworkFromConn added in v0.13.0

func NetworkFromConn(c net.Conn) string

func NoSuchHost added in v0.13.0

func NoSuchHost(host, srv string) *net.DNSError

NoSuchHost returns a net.Error representing a DNS lookup failure for the specified host. The host parameter is the hostname that was looked up (e.g. example.com). The srv parameter is the DNS server address (e.g. 8.8.8.8:53).

func NormalNet added in v0.13.0

func NormalNet(network string) string

NormalNet normalizes a network string by removing the IP version suffix. For example, "tcp4" becomes "tcp", "udp6" becomes "udp", and "ip4" becomes "ip".

func PickIP added in v0.13.0

func PickIP(ips []net.IP, prefer int) net.IP

PickIP selects an IP address from the given list based on preference. If prefer is 4, IPv4 addresses are preferred; if 6, IPv6 addresses are preferred. If no preference is specified (prefer != 4 && prefer != 6), a random IP is returned. If the preferred family is not available, an IP from the other family is returned.

func PipeConn added in v0.13.0

func PipeConn(inc, out net.Conn) (err error)

PipeConn copies data bidirectionally between two connections.

PipeConn establishes a full-duplex pipe between two connections, copying data from inc->out and out->inc concurrently. It blocks until both directions complete or an error occurs and returns the first error encountered (if any).

func PipePacketConn added in v0.13.0

func PipePacketConn(
	inc, out net.PacketConn,
	bufSize int,
	pool bufpool.Pool,
) (err error)

PipePacketConn copies packets bidirectionally between two packet connections.

PipePacketConn establishes a full-duplex pipe between two packet connections, copying packets from inc->out and out->inc concurrently. Unlike PipeConn, this function preserves packet boundaries by reading and writing individual datagrams. It blocks until both directions complete or an error occurs and returns the first error encountered (if any).

func ReadNullTerminatedString added in v0.13.0

func ReadNullTerminatedString(r io.Reader, buf []byte) (string, error)

ReadNullTerminatedString reads bytes from r until a null byte (0x00) is encountered. It returns the resulting string (excluding the null terminator). An error is returned if the string exceeds buf's capacity or if reading fails.

func ReadUntilClose added in v0.13.0

func ReadUntilClose(rc io.ReadCloser)

ReadUntilClose reads from rc until an error occurs, then closes rc. This function is useful for draining a connection before closing it.

func SplitHostPort added in v0.13.0

func SplitHostPort(
	network, hostport string,
	defport uint16,
) (host string, port uint16)

SplitHostPort splits a host:port string into host and port components. If no port is present or the port is invalid, defport is used as the default. The network parameter is used for service name lookup via LookupPortOffline.

func SyscallConn added in v0.13.0

func SyscallConn(a any) (syscall.RawConn, error)

SyscallConn returns the underlying syscall.RawConn from a connection. It checks if the value implements the withSyscall interface, or unwraps the value to find one that does. Returns nil if the value is nil or doesn't implement the interface.

func TrueFilter

func TrueFilter(_, _ string) bool

TrueFilter is a Filter that always returns true.

func UnfuckGoDns

func UnfuckGoDns()

UnfuckGoDns sets GODEBUG=netedns0=0 to disable EDNS0 extension unsupported by a lot of consumer routers but still used by go resolver by default for some fucking reason. And there is no ways to disable it with Resolver methods/fields or something.

Some related links:

It is safe to use UnfuckGoDns with already set GODEBUG var. UnfuckGoDns only appends netedns0=0 if netedns0 is not set. It doesn't alter other fields and do nothing if netedns0 is already set.

Types

type CallbackConn

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

CallbackConn wraps a net.Conn and invokes callbacks on events.

func (*CallbackConn) Close

func (c *CallbackConn) Close() error

Close calls the BeforeClose callback, then closes the underlying connection.

func (*CallbackConn) GetWrapped

func (c *CallbackConn) GetWrapped() any

GetWrapped returns the underlying wrapped connection.

type CallbackListener

type CallbackListener struct {
	net.Listener
	// contains filtered or unexported fields
}

CallbackListener wraps a net.Listener and invokes callbacks on events.

func (*CallbackListener) Accept

func (c *CallbackListener) Accept() (net.Conn, error)

Accept accepts a connection and invokes OnAccept if the callback is set.

func (*CallbackListener) Close

func (c *CallbackListener) Close() error

Close calls the BeforeClose callback, then closes the underlying listener.

func (*CallbackListener) GetWrapped

func (c *CallbackListener) GetWrapped() any

GetWrapped returns the underlying wrapped listener.

type CallbackNetPacketConn

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

CallbackNetPacketConn wraps a net.PacketConn and invokes callbacks on events.

func (*CallbackNetPacketConn) Close

func (c *CallbackNetPacketConn) Close() error

Close calls the BeforeClose callback, then closes the underlying connection.

func (*CallbackNetPacketConn) GetWrapped

func (c *CallbackNetPacketConn) GetWrapped() any

GetWrapped returns the underlying wrapped connection.

type CallbackPacketConn

type CallbackPacketConn struct {
	PacketConn
	// contains filtered or unexported fields
}

CallbackPacketConn wraps a PacketConn and invokes callbacks on events.

func (*CallbackPacketConn) Close

func (c *CallbackPacketConn) Close() error

Close calls the BeforeClose callback, then closes the underlying connection.

func (*CallbackPacketConn) GetWrapped

func (c *CallbackPacketConn) GetWrapped() any

GetWrapped returns the underlying wrapped connection.

type CallbackTCPConn

type CallbackTCPConn struct {
	TCPConn
	// contains filtered or unexported fields
}

CallbackTCPConn wraps a net.TCPConn and invokes callbacks on events.

func (*CallbackTCPConn) Close

func (c *CallbackTCPConn) Close() error

Close calls the BeforeClose callback, then closes the underlying connection.

func (*CallbackTCPConn) GetWrapped

func (c *CallbackTCPConn) GetWrapped() any

GetWrapped returns the underlying wrapped connection.

type CallbackTCPListener

type CallbackTCPListener struct {
	TCPListener
	// contains filtered or unexported fields
}

CallbackTCPListener wraps a net.TCPListener and invokes callbacks on events.

func (*CallbackTCPListener) Accept

func (c *CallbackTCPListener) Accept() (net.Conn, error)

Accept accepts a connection and invokes OnAccept if the callback is set.

func (*CallbackTCPListener) AcceptTCP

func (c *CallbackTCPListener) AcceptTCP() (TCPConn, error)

AcceptTCP accepts a TCP connection and invokes OnAcceptTCP if the callback is set.

func (*CallbackTCPListener) Close

func (c *CallbackTCPListener) Close() error

Close calls the BeforeClose callback, then closes the underlying listener.

func (*CallbackTCPListener) GetWrapped

func (c *CallbackTCPListener) GetWrapped() any

GetWrapped returns the underlying wrapped listener.

type CallbackUDPConn

type CallbackUDPConn struct {
	UDPConn
	// contains filtered or unexported fields
}

CallbackUDPConn wraps a net.UDPConn and invokes callbacks on events.

func (*CallbackUDPConn) Close

func (c *CallbackUDPConn) Close() error

Close calls the BeforeClose callback, then closes the underlying connection.

func (*CallbackUDPConn) GetWrapped

func (c *CallbackUDPConn) GetWrapped() any

GetWrapped returns the underlying wrapped connection.

type Callbacks

type Callbacks struct {
	// BeforeClose is called before the connection or listener is closed.
	BeforeClose func()
	// OnAccept is called when a listener accepts a new connection.
	// The callback can return a different connection or an error to reject it.
	OnAccept func(net.Conn) (net.Conn, error)
	// OnAcceptTCP is called when a TCP listener accepts a new TCP connection.
	// The callback can return a different TCP connection or an error to reject it.
	OnAcceptTCP func(TCPConn) (TCPConn, error)
}

Callbacks holds callback functions invoked on various network events.

func (*Callbacks) RunBeforeClose

func (c *Callbacks) RunBeforeClose()

func (*Callbacks) RunOnAccept

func (c *Callbacks) RunOnAccept(conn net.Conn) (net.Conn, error)

func (*Callbacks) RunOnAcceptTCP

func (c *Callbacks) RunOnAcceptTCP(conn TCPConn) (TCPConn, error)

type CloserSubscriber added in v0.15.0

type CloserSubscriber interface {
	SubscribeCloser(c io.Closer) (func(), error)
}

CloserSubscriber is implemented by Network values that can attach externally created closers to their own lifecycle.

SubscribeCloser registers c to be closed when the Network is permanently closed. The returned unsubscribe function removes c without closing it. If the Network is already closed, c is closed before SubscribeCloser returns net.ErrClosed.

Network implementations that also implement io.Closer must implement CloserSubscriber.

type ControlFlags added in v0.13.0

type ControlFlags int
const (
	ControlDst ControlFlags = 1 << iota
	ControlInterface
)

type ControlMessage added in v0.13.0

type ControlMessage struct {
	Dst     net.Addr
	IfIndex int
	IfName  string
}

type CustomFilter

type CustomFilter struct {
	Hosts []HostFilterEntry
	IPs   []IpFilterEntry
	CIDRs []*net.IPNet
}

CustomFilter is a Filter that matches addresses based on a set of patterns. Patterns are similar to the NO_PROXY environment variable format.

func FilterFromString

func FilterFromString(str string) CustomFilter

FilterFromString creates a CustomFilter from a comma-separated string.

Each entry can be:

  • host:port - matches this host and port combination
  • host - matches this host on any port
  • ip - matches this exact IP address
  • ip/subnet - matches any IP in this CIDR subnet
  • Wildcards (*, ?) are supported in host patterns using shell glob matching

Examples:

  • "localhost,127.0.0.1" - true for localhost and IPv4 loopback
  • "*.example.com" - true for all subdomains of example.com
  • "192.168.0.0/16" - true for entire 192.168.x.x subnet
  • "internal.corp:8080" - true for specific host:port

The filter is case-insensitive and handles both bracketed IPv6 addresses (e.g., [::1]:8080) and trailing dots in hostnames.

func (CustomFilter) Filter

func (f CustomFilter) Filter(network, address string) bool

Filter implements the Filter function for CustomFilter.

type DetachedNetwork added in v0.13.0

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

DetachedNetwork is an independently stoppable wrapper around a Network.

Down and Close affect only the wrapper: they do not call Down or Close on the wrapped Network. They do cancel in-flight wrapper operations and close every connection, packet connection, listener, and accepted connection returned via this wrapper. Close is terminal: a closed wrapper cannot be brought back up. Multiple DetachedNetwork values can wrap the same Network and be used concurrently; stopping one wrapper does not stop the others.

Long operations such as Dial, Listen, and Lookup are run without holding the wrapper mutex. The wrapper injects its own cancellation into the supplied context so a concurrent Down or Close can unblock operations that honor context cancellation.

func DetachNetwork added in v0.13.0

func DetachNetwork(n Network) *DetachedNetwork

DetachNetwork creates an independently stoppable wrapper around n.

func (*DetachedNetwork) Close added in v0.13.0

func (n *DetachedNetwork) Close() error

Close permanently closes this wrapper.

func (*DetachedNetwork) Dial added in v0.13.0

func (n *DetachedNetwork) Dial(
	ctx context.Context,
	network, address string,
) (net.Conn, error)

Dial establishes a connection via the wrapped Network and tracks it on this wrapper.

func (*DetachedNetwork) DialTCP added in v0.13.0

func (n *DetachedNetwork) DialTCP(
	ctx context.Context,
	network, laddr, raddr string,
) (TCPConn, error)

DialTCP establishes a TCP connection via the wrapped Network.

func (*DetachedNetwork) DialUDP added in v0.13.0

func (n *DetachedNetwork) DialUDP(
	ctx context.Context,
	network, laddr, raddr string,
) (UDPConn, error)

DialUDP establishes a UDP connection via the wrapped Network.

func (*DetachedNetwork) Down added in v0.13.0

func (n *DetachedNetwork) Down() error

Down stops this wrapper, cancels pending wrapper operations, and closes all objects spawned through it. It does not call Down on the wrapped Network.

func (*DetachedNetwork) GetWrapped added in v0.13.0

func (n *DetachedNetwork) GetWrapped() any

GetWrapped returns the wrapped Network.

func (*DetachedNetwork) InterfaceAddrs added in v0.13.0

func (n *DetachedNetwork) InterfaceAddrs() ([]net.Addr, error)

func (*DetachedNetwork) InterfaceMulticastAddrs added in v0.13.0

func (n *DetachedNetwork) InterfaceMulticastAddrs() ([]net.Addr, error)

func (*DetachedNetwork) Interfaces added in v0.13.0

func (n *DetachedNetwork) Interfaces() ([]NetworkInterface, error)

func (*DetachedNetwork) InterfacesByIndex added in v0.13.0

func (n *DetachedNetwork) InterfacesByIndex(
	index int,
) ([]NetworkInterface, error)

func (*DetachedNetwork) InterfacesByName added in v0.13.0

func (n *DetachedNetwork) InterfacesByName(
	name string,
) ([]NetworkInterface, error)

func (*DetachedNetwork) IsNative added in v0.13.0

func (n *DetachedNetwork) IsNative() bool

IsNative reports the wrapped Network native status.

func (*DetachedNetwork) IsUp added in v0.13.0

func (n *DetachedNetwork) IsUp() (bool, error)

IsUp reports whether this wrapper is currently up.

func (*DetachedNetwork) Listen added in v0.13.0

func (n *DetachedNetwork) Listen(
	ctx context.Context,
	network, address string,
) (net.Listener, error)

Listen creates a listener via the wrapped Network and tracks it on this wrapper. Accepted connections are also tracked by this wrapper.

func (*DetachedNetwork) ListenMulticastUDP added in v0.13.0

func (n *DetachedNetwork) ListenMulticastUDP(
	ctx context.Context,
	network, address string,
	opts MulticastOptions,
) (MulticastPacketConn, error)

func (*DetachedNetwork) ListenPacket added in v0.13.0

func (n *DetachedNetwork) ListenPacket(
	ctx context.Context,
	network, address string,
) (PacketConn, error)

ListenPacket creates and tracks a packet listener via the wrapped Network.

func (*DetachedNetwork) ListenPacketConfig added in v0.13.0

func (n *DetachedNetwork) ListenPacketConfig(
	ctx context.Context,
	lc *ListenConfig,
	network, address string,
) (PacketConn, error)

ListenPacketConfig creates and tracks a configured packet listener via the wrapped Network.

func (*DetachedNetwork) ListenTCP added in v0.13.0

func (n *DetachedNetwork) ListenTCP(
	ctx context.Context,
	network, laddr string,
) (TCPListener, error)

ListenTCP creates and tracks a TCP listener via the wrapped Network.

func (*DetachedNetwork) ListenUDP added in v0.13.0

func (n *DetachedNetwork) ListenUDP(
	ctx context.Context,
	network, laddr string,
) (UDPConn, error)

ListenUDP creates and tracks a UDP connection via the wrapped Network.

func (*DetachedNetwork) ListenUDPConfig added in v0.13.0

func (n *DetachedNetwork) ListenUDPConfig(
	ctx context.Context,
	lc *ListenConfig,
	network, laddr string,
) (UDPConn, error)

ListenUDPConfig creates and tracks a configured UDP listener via the wrapped Network.

func (*DetachedNetwork) LookupAddr added in v0.13.0

func (n *DetachedNetwork) LookupAddr(
	ctx context.Context,
	addr string,
) ([]string, error)

func (*DetachedNetwork) LookupCNAME added in v0.13.0

func (n *DetachedNetwork) LookupCNAME(
	ctx context.Context,
	host string,
) (string, error)

func (*DetachedNetwork) LookupHost added in v0.13.0

func (n *DetachedNetwork) LookupHost(
	ctx context.Context,
	host string,
) ([]string, error)

func (*DetachedNetwork) LookupIP added in v0.13.0

func (n *DetachedNetwork) LookupIP(
	ctx context.Context,
	network, address string,
) ([]net.IP, error)

func (*DetachedNetwork) LookupIPAddr added in v0.13.0

func (n *DetachedNetwork) LookupIPAddr(
	ctx context.Context,
	host string,
) ([]net.IPAddr, error)

func (*DetachedNetwork) LookupMX added in v0.13.0

func (n *DetachedNetwork) LookupMX(
	ctx context.Context,
	name string,
) ([]*net.MX, error)

func (*DetachedNetwork) LookupNS added in v0.13.0

func (n *DetachedNetwork) LookupNS(
	ctx context.Context,
	name string,
) ([]*net.NS, error)

func (*DetachedNetwork) LookupNetIP added in v0.13.0

func (n *DetachedNetwork) LookupNetIP(
	ctx context.Context,
	network, host string,
) ([]netip.Addr, error)

func (*DetachedNetwork) LookupPort added in v0.13.0

func (n *DetachedNetwork) LookupPort(
	ctx context.Context,
	network, service string,
) (int, error)

func (*DetachedNetwork) LookupSRV added in v0.13.0

func (n *DetachedNetwork) LookupSRV(
	ctx context.Context,
	service, proto, name string,
) (string, []*net.SRV, error)

func (*DetachedNetwork) LookupTXT added in v0.13.0

func (n *DetachedNetwork) LookupTXT(
	ctx context.Context,
	name string,
) ([]string, error)

func (*DetachedNetwork) PacketDial added in v0.13.0

func (n *DetachedNetwork) PacketDial(
	ctx context.Context,
	network, address string,
) (PacketConn, error)

PacketDial establishes a packet connection via the wrapped Network.

func (*DetachedNetwork) SubscribeCloser added in v0.13.0

func (n *DetachedNetwork) SubscribeCloser(c io.Closer) (func(), error)

SubscribeCloser registers c to be closed when this wrapper is closed.

It is intended for callers that bypass this Network's Dial or Listen methods but still want their externally-created connections to be closed by Close. The returned unsubscribe function removes c from this wrapper without closing it. If this Network is already closed, c is closed before SubscribeCloser returns net.ErrClosed.

func (*DetachedNetwork) SubscribeUpDown added in v0.15.0

func (n *DetachedNetwork) SubscribeUpDown(u UpDown) (func(), error)

SubscribeUpDown registers u to follow this wrapper's up/down state.

The returned unsubscribe function removes u without changing it. The subscription persists across Down and Up cycles. If this wrapper is already down or closed, u.Down is called before SubscribeUpDown returns.

func (*DetachedNetwork) Up added in v0.13.0

func (n *DetachedNetwork) Up() error

Up re-enables this wrapper. It does not call Up on the wrapped Network.

type Dial

type Dial = func(ctx context.Context, network, address string) (net.Conn, error)

Dial is a function type for establishing TCP-like connections. It matches the signature of net.Dialer.DialContext.

type DialTCP

type DialTCP = func(
	ctx context.Context,
	network, laddr, raddr string,
) (TCPConn, error)

DialTCP establishes a TCP connection similar to net.Dial for TCP networks.

type DialUDP

type DialUDP = func(
	ctx context.Context,
	network, laddr, raddr string,
) (UDPConn, error)

DialUDP creates a UDP connection similar to net.Dial for UDP networks.

type DnsServer

type DnsServer struct {
	// Net is the network type to use (e.g., "udp", "tcp").
	// If empty, defaults to "udp".
	Net string
	// Addr is the address of the DNS server (e.g., "8.8.8.8:53" or "1.1.1.1").
	// By default port is 53 so it can be omitted.
	Addr string
}

DnsServer specifies a custom DNS server to use for resolution.

type Filter

type Filter = func(network, address string) bool

Filter functions are used whenever different handling should be applied to connections/requests depending on their network and address. For example, a proxy can use a filter to decide whether a connection should be passed directly (true) or proxied (false), or to block/allow, etc.

Network may be "" if unknown.

func InvertFilter

func InvertFilter(filter Filter) Filter

InvertFilter is a Filter that returns iverted result of filter.

func OrFilter

func OrFilter(filters ...Filter) Filter

OrFilter is a Filter that returns true if any of filters do it.

type HostFilterEntry

type HostFilterEntry struct {
	Pattern  string // wildcard pattern, lowercased, no trailing dot
	WithPort bool
	Port     string
}

type IpFilterEntry

type IpFilterEntry struct {
	IP       net.IP
	WithPort bool
	Port     string
}

type Listen

type Listen = func(ctx context.Context, network, address string) (net.Listener, error)

Listen is a function type for creating TCP-like listeners.

type ListenConfig added in v0.8.0

type ListenConfig struct {
	// Some virtual Network implementations may ignore Control function or
	// call it with nil syscall.RawConn if they are not wrapping real syscalls.
	Control func(network, address string, c syscall.RawConn) error
}

type ListenTCP

type ListenTCP = func(
	ctx context.Context,
	network, laddr string,
) (TCPListener, error)

ListenTCP announces and returns a listener for TCP connections.

type ListenUDP

type ListenUDP = func(
	ctx context.Context,
	network, laddr string,
) (UDPConn, error)

ListenUDP announces and returns a packet-oriented UDP connection.

type LiteralInterface

type LiteralInterface struct {
	IDVal             string
	IndexVal          int
	NameVal           string
	MTUVal            int
	HardwareAddrVal   net.HardwareAddr
	FlagsVal          net.Flags
	AddrsVal          []net.Addr
	MulticastAddrsVal []net.Addr
}

func (*LiteralInterface) Addrs

func (i *LiteralInterface) Addrs() ([]net.Addr, error)

func (*LiteralInterface) Flags

func (i *LiteralInterface) Flags() net.Flags

func (*LiteralInterface) HardwareAddr

func (i *LiteralInterface) HardwareAddr() net.HardwareAddr

func (*LiteralInterface) ID

func (i *LiteralInterface) ID() string

func (*LiteralInterface) Index

func (i *LiteralInterface) Index() int

func (*LiteralInterface) MTU

func (i *LiteralInterface) MTU() int

func (*LiteralInterface) MulticastAddrs

func (i *LiteralInterface) MulticastAddrs() ([]net.Addr, error)

func (*LiteralInterface) Name

func (i *LiteralInterface) Name() string

type LookupAddr

type LookupAddr = func(ctx context.Context, addr string) (names []string, err error)

LookupAddr performs a reverse lookup for the given address, returning a list of names mapping to that address.

type LookupCNAME

type LookupCNAME = func(ctx context.Context, host string) (cname string, err error)

LookupCNAME returns the canonical name for the given host.

type LookupHost

type LookupHost = func(ctx context.Context, host string) (addrs []string, err error)

LookupHost looks up host just like LookupIP but unlike it returns slice of IP strings.

type LookupIP

type LookupIP = func(ctx context.Context, network, address string) ([]net.IP, error)

LookupIP looks up host. It returns a slice of that host's IPv4 and IPv6 addresses.

type LookupIPAddr

type LookupIPAddr = func(ctx context.Context, host string) ([]net.IPAddr, error)

LookupIPAddr looks up host just like LookupIP but unlike it returns slice of net.IPAddr.

type LookupMX

type LookupMX = func(ctx context.Context, name string) ([]*net.MX, error)

LookupMX returns the DNS MX records for the given domain name sorted by preference.

type LookupNS

type LookupNS = func(ctx context.Context, name string) ([]*net.NS, error)

LookupNS returns the DNS NS records for the given domain name.

type LookupNetIP

type LookupNetIP = func(ctx context.Context, network, host string) ([]netip.Addr, error)

LookupNetIP looks up host just like LookupIP but unlike it returns slice of netip.Addr.

type LookupPort

type LookupPort = func(ctx context.Context, network, service string) (port int, err error)

LookupPort looks up the port for the given network and service.

type LookupSRV

type LookupSRV = func(ctx context.Context, service, proto, name string) (string, []*net.SRV, error)

LookupSRV tries to resolve an SRV query of the given service, protocol, and domain name. The proto is "tcp" or "udp".

type LookupTXT

type LookupTXT = func(ctx context.Context, name string) ([]string, error)

LookupTXT returns the DNS TXT records for the given domain name. If a DNS TXT record holds multiple strings, they are concatenated as a single string.

type LoopbackNetwork added in v0.13.0

type LoopbackNetwork struct {

	// AllowAnyHost rewrites non-loopback host names and addresses to localhost
	// before Dial and Listen style address normalization. It is false by
	// default to preserve the historical loopback resolver behavior.
	AllowAnyHost bool
	// contains filtered or unexported fields
}

LoopbackNetwork is an in-memory network implementation that simulates loopback network operations. It provides TCP and UDP communication using buffered in-memory transports for TCP and buffered channels for UDP, all without creating actual network sockets.

func NewLoopbackNetwok added in v0.13.0

func NewLoopbackNetwok() *LoopbackNetwork

NewLoopbackNetwok creates and returns a new loopback network instance. The returned network provides simulated TCP and UDP communication on IPv4 (127.0.0.1) and IPv6 (::1) loopback addresses.

func (*LoopbackNetwork) Close added in v0.15.0

func (ln *LoopbackNetwork) Close() error

Close permanently closes this network.

func (*LoopbackNetwork) Dial added in v0.13.0

func (ln *LoopbackNetwork) Dial(
	ctx context.Context,
	network, address string,
) (net.Conn, error)

Dial establishes a connection to the address on the specified network. It routes to DialTCP for TCP networks ("tcp", "tcp4", "tcp6") or to DialUDP for UDP networks ("udp", "udp4", "udp6"). Returns an error for unknown network types.

func (*LoopbackNetwork) DialTCP added in v0.13.0

func (ln *LoopbackNetwork) DialTCP(
	ctx context.Context,
	network, laddr, raddr string,
) (TCPConn, error)

DialTCP establishes a TCP connection to the remote address using the specified network. It accepts "tcp", "tcp4", or "tcp6" as valid network types. If laddr is not empty, it is used as the local address for the connection. The connection is established using a buffered in-memory transport between the client and server. Returns an error if no listener is bound to the remote address.

func (*LoopbackNetwork) DialUDP added in v0.13.0

func (ln *LoopbackNetwork) DialUDP(
	ctx context.Context,
	network, laddr, raddr string,
) (UDPConn, error)

DialUDP establishes a UDP connection to the remote address using the specified network. It accepts "udp", "udp4", or "udp6" as valid network types. If laddr is not empty, it is used as the local address for the connection. The returned UDPConn is an in-memory UDP connection that communicates via buffered channels.

func (*LoopbackNetwork) Down added in v0.13.0

func (ln *LoopbackNetwork) Down() error

Down shuts down the network by closing all tracked connections and listeners. After calling Down, the network will reject new operations until Up() is called.

func (*LoopbackNetwork) InterfaceAddrs added in v0.13.0

func (ln *LoopbackNetwork) InterfaceAddrs() ([]net.Addr, error)

InterfaceAddrs returns the unicast interface addresses for the loopback interface. It returns the IPv4 loopback range 127.0.0.0/8 to be permissive and the IPv6 loopback address.

func (*LoopbackNetwork) InterfaceMulticastAddrs added in v0.13.0

func (ln *LoopbackNetwork) InterfaceMulticastAddrs() ([]net.Addr, error)

InterfaceMulticastAddrs returns multicast addresses for the loopback interface.

func (*LoopbackNetwork) Interfaces added in v0.13.0

func (ln *LoopbackNetwork) Interfaces() ([]NetworkInterface, error)

Interfaces returns a slice containing the loopback network interface. It returns a single interface representing "lo" with index 1, MTU 65536, and the net.FlagLoopback and net.FlagUp flags set.

func (*LoopbackNetwork) InterfacesByIndex added in v0.13.0

func (ln *LoopbackNetwork) InterfacesByIndex(
	index int,
) ([]NetworkInterface, error)

InterfacesByIndex returns the network interface with the given index. It returns the loopback interface only if index is 1, otherwise returns an error indicating the interface was not found.

func (*LoopbackNetwork) InterfacesByName added in v0.13.0

func (ln *LoopbackNetwork) InterfacesByName(
	name string,
) ([]NetworkInterface, error)

InterfacesByName returns the network interface with the given name. It returns the loopback interface only if name is "lo", otherwise returns an error indicating the interface was not found.

func (*LoopbackNetwork) IsNative added in v0.13.0

func (ln *LoopbackNetwork) IsNative() bool

func (*LoopbackNetwork) IsUp added in v0.13.0

func (ln *LoopbackNetwork) IsUp() (bool, error)

IsUp returns whether the network is currently active.

func (*LoopbackNetwork) Listen added in v0.13.0

func (ln *LoopbackNetwork) Listen(
	ctx context.Context,
	network, address string,
) (net.Listener, error)

Listen announces on the specified network and address. It delegates to ListenTCP for TCP-based networks. The returned listener is wrapped with loopback-specific error handling.

func (*LoopbackNetwork) ListenMulticastUDP added in v0.13.0

func (ln *LoopbackNetwork) ListenMulticastUDP(
	ctx context.Context,
	network, address string,
	opts MulticastOptions,
) (MulticastPacketConn, error)

func (*LoopbackNetwork) ListenPacket added in v0.13.0

func (ln *LoopbackNetwork) ListenPacket(
	ctx context.Context,
	network, address string,
) (PacketConn, error)

ListenPacket announces on the specified network and address for packet-oriented protocols. It delegates to ListenUDP for UDP-based networks. The returned PacketConn is wrapped with loopback-specific error handling.

func (*LoopbackNetwork) ListenPacketConfig added in v0.13.0

func (ln *LoopbackNetwork) ListenPacketConfig(
	ctx context.Context,
	lc *ListenConfig,
	network, address string,
) (PacketConn, error)

ListenPacketConfig announces on the specified network and address for packet-oriented protocols. Loopback networking has no socket control layer, so lc is accepted for interface compatibility and otherwise ignored.

func (*LoopbackNetwork) ListenTCP added in v0.13.0

func (ln *LoopbackNetwork) ListenTCP(
	ctx context.Context,
	network, laddr string,
) (TCPListener, error)

ListenTCP announces on the specified TCP network and address. It accepts "tcp", "tcp4", or "tcp6" as valid network types. The returned TCPListener is an in-memory listener that accepts connections via a buffered in-memory TCP transport.

func (*LoopbackNetwork) ListenUDP added in v0.13.0

func (ln *LoopbackNetwork) ListenUDP(
	ctx context.Context,
	network, laddr string,
) (UDPConn, error)

ListenUDP announces on the specified UDP network and address. It accepts "udp", "udp4", or "udp6" as valid network types. The returned UDPConn is an in-memory UDP connection that communicates via buffered channels.

func (*LoopbackNetwork) ListenUDPConfig added in v0.13.0

func (ln *LoopbackNetwork) ListenUDPConfig(
	ctx context.Context,
	lc *ListenConfig,
	network, laddr string,
) (UDPConn, error)

ListenUDPConfig announces on the specified UDP network and address. Loopback networking has no socket control layer, so lc is accepted for interface compatibility and otherwise ignored.

func (*LoopbackNetwork) LookupAddr added in v0.13.0

func (ln *LoopbackNetwork) LookupAddr(
	ctx context.Context, addr string,
) (names []string, err error)

LookupAddr performs a reverse lookup for the given address. It returns ["localhost"] for local addresses, or an error for non-local addresses.

func (*LoopbackNetwork) LookupCNAME added in v0.13.0

func (ln *LoopbackNetwork) LookupCNAME(
	ctx context.Context, host string,
) (cname string, err error)

LookupCNAME returns an error indicating no CNAME exists for the given host. The loopback network does not support DNS CNAME lookups.

func (*LoopbackNetwork) LookupHost added in v0.13.0

func (ln *LoopbackNetwork) LookupHost(
	ctx context.Context, host string,
) (addrs []string, err error)

LookupHost looks up the host and returns a slice of IP address strings. It returns ["127.0.0.1", "::1"] for local hosts, or an error for non-local hosts.

func (*LoopbackNetwork) LookupIP added in v0.13.0

func (ln *LoopbackNetwork) LookupIP(
	ctx context.Context, network, address string,
) (addrs []net.IP, err error)

LookupIP looks up the host and returns a slice of net.IP values. The network parameter specifies the IP version: "ip4" returns IPv4 only, "ip6" returns IPv6 only, and other values return both IPv4 and IPv6. Returns an error for non-local addresses.

func (*LoopbackNetwork) LookupIPAddr added in v0.13.0

func (ln *LoopbackNetwork) LookupIPAddr(
	ctx context.Context, host string,
) (addrs []net.IPAddr, err error)

LookupIPAddr looks up the host and returns a slice of net.IPAddr values. It returns both IPv4 and IPv6 loopback addresses for local hosts, or an error for non-local hosts.

func (*LoopbackNetwork) LookupMX added in v0.13.0

func (ln *LoopbackNetwork) LookupMX(
	ctx context.Context,
	name string,
) ([]*net.MX, error)

LookupMX returns an error indicating no MX records exist for the given name. The loopback network does not support DNS MX record lookups.

func (*LoopbackNetwork) LookupNS added in v0.13.0

func (ln *LoopbackNetwork) LookupNS(
	ctx context.Context,
	name string,
) ([]*net.NS, error)

LookupNS returns an error indicating no NS records exist for the given name. The loopback network does not support DNS NS record lookups.

func (*LoopbackNetwork) LookupNetIP added in v0.13.0

func (ln *LoopbackNetwork) LookupNetIP(
	ctx context.Context, network, address string,
) (addrs []netip.Addr, err error)

LookupNetIP looks up the host and returns a slice of netip.Addr values. The network parameter specifies the IP version: "ip4" returns IPv4 only, "ip6" returns IPv6 only, and other values return both IPv4 and IPv6. Returns an error for non-local addresses.

func (*LoopbackNetwork) LookupPort added in v0.13.0

func (ln *LoopbackNetwork) LookupPort(
	ctx context.Context, network, service string,
) (port int, err error)

LookupPort looks up the port number for the given network and service. It delegates to gonnect.LookupPortOffline for offline port resolution.

func (*LoopbackNetwork) LookupSRV added in v0.13.0

func (ln *LoopbackNetwork) LookupSRV(
	ctx context.Context,
	service, proto, name string,
) (string, []*net.SRV, error)

LookupSRV returns an error indicating no SRV records exist for the given service. The loopback network does not support DNS SRV record lookups.

func (*LoopbackNetwork) LookupTXT added in v0.13.0

func (ln *LoopbackNetwork) LookupTXT(
	ctx context.Context,
	name string,
) ([]string, error)

LookupTXT returns an empty slice for local addresses, or an error for non-local addresses. The loopback network does not support DNS TXT record lookups for external hosts.

func (*LoopbackNetwork) PacketDial added in v0.13.0

func (ln *LoopbackNetwork) PacketDial(
	ctx context.Context, network, address string,
) (PacketConn, error)

PacketDial establishes a UDP connection to the remote address using the specified network. The returned PacketConn is wrapped with callbacks for automatic tracking.

func (*LoopbackNetwork) SubscribeCloser added in v0.15.0

func (ln *LoopbackNetwork) SubscribeCloser(c io.Closer) (func(), error)

SubscribeCloser registers c to be closed when this network is closed.

The returned unsubscribe function removes c without closing it. If this network is already closed, c is closed before SubscribeCloser returns net.ErrClosed.

func (*LoopbackNetwork) SubscribeUpDown added in v0.15.0

func (ln *LoopbackNetwork) SubscribeUpDown(u UpDown) (func(), error)

SubscribeUpDown registers u to follow this network's up/down state.

The returned unsubscribe function removes u without changing it. The subscription persists across Down and Up cycles. If this network is already down or closed, u.Down is called before SubscribeUpDown returns.

func (*LoopbackNetwork) Up added in v0.13.0

func (ln *LoopbackNetwork) Up() error

Up re-enables the network after it has been shut down with Down().

type MulticastOptions added in v0.13.0

type MulticastOptions struct {
	ReuseAddr bool
	ReusePort bool
	RecvAnyIf bool

	ControlFlags ControlFlags
}

type MulticastPacketConn added in v0.13.0

type MulticastPacketConn interface {
	net.PacketConn

	JoinGroup(iface NetworkInterface, group net.Addr) error
	LeaveGroup(iface NetworkInterface, group net.Addr) error

	SetControlMessage(flags ControlFlags, on bool) error
	ReadFromControl(
		b []byte,
	) (n int, cm ControlMessage, from net.Addr, err error)
	WriteToControl(b []byte, cm ControlMessage, dst net.Addr) (int, error)
}

type NativeConfig added in v0.13.0

type NativeConfig struct {
	// Filter is an optional filter function that can reject network operations.
	// It should return true to reject the operation.
	//
	// NOTE: filtering works only for connections establishing, unbinded DNS sockset can be used to bypass it
	Filter Filter
	// ResolverCfg configures the DNS resolver used by the Network.
	// If nil, new one will be built.
	ResolverCfg *ResolverCfg

	// PreferIP specifies IP version preference:
	// 4 for IPv4, 6 for IPv6, or 0 for no preference.
	PreferIP int

	// ListenCfg configures the listen operations. If nil, defaults are used.
	ListenCfg *net.ListenConfig

	// net.Dialer options
	Timeout         time.Duration
	Deadline        time.Time
	LocalAddr       net.Addr
	FallbackDelay   time.Duration
	KeepAlive       time.Duration
	KeepAliveConfig net.KeepAliveConfig
	Control         func(network, address string, c syscall.RawConn) error
	ControlContext  func(ctx context.Context, network, address string, c syscall.RawConn) error
}

NativeConfig holds configuration options for building a Network.

func (NativeConfig) Build added in v0.13.0

func (c NativeConfig) Build() *NativeNetwork

Build creates and returns a new NativeNetwork instance from the configuration.

type NativeInterface

type NativeInterface struct {
	Iface net.Interface
}

func (*NativeInterface) Addrs

func (i *NativeInterface) Addrs() ([]net.Addr, error)

func (*NativeInterface) Flags

func (i *NativeInterface) Flags() net.Flags

func (*NativeInterface) HardwareAddr

func (i *NativeInterface) HardwareAddr() net.HardwareAddr

func (*NativeInterface) ID

func (i *NativeInterface) ID() string

func (*NativeInterface) Index

func (i *NativeInterface) Index() int

func (*NativeInterface) MTU

func (i *NativeInterface) MTU() int

func (*NativeInterface) MulticastAddrs

func (i *NativeInterface) MulticastAddrs() ([]net.Addr, error)

func (*NativeInterface) Name

func (i *NativeInterface) Name() string

type NativeNetwork added in v0.13.0

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

NativeNetwork is a filtered network provider that implements Network. It wraps Go's standard net package to provide controlled dialing, listening, and DNS resolution with optional filtering.

NativeNetwork does not implement UpDown. Wrap it with DetachNetwork when an independently stoppable native network is needed:

n := DetachNetwork(NativeConfig{}.Build())

func (*NativeNetwork) Dial added in v0.13.0

func (n *NativeNetwork) Dial(
	ctx context.Context,
	network, address string,
) (net.Conn, error)

Dial establishes a connection to the address on the specified network. It applies filtering before dialing.

func (*NativeNetwork) DialTCP added in v0.13.0

func (n *NativeNetwork) DialTCP(
	ctx context.Context,
	network, laddr, raddr string,
) (TCPConn, error)

DialTCP establishes a TCP connection to the remote address using the specified network. If laddr is not empty, it is used as the local address for the connection.

func (*NativeNetwork) DialUDP added in v0.13.0

func (n *NativeNetwork) DialUDP(
	ctx context.Context,
	network, laddr, raddr string,
) (UDPConn, error)

DialUDP establishes a UDP connection to the remote address using the specified network. If laddr is not empty, it is used as the local address for the connection.

func (*NativeNetwork) InterfaceAddrs added in v0.13.0

func (n *NativeNetwork) InterfaceAddrs() ([]net.Addr, error)

InterfaceAddrs returns the unicast interface addresses associated with the system. This method delegates to net.InterfaceAddrs.

func (*NativeNetwork) InterfaceMulticastAddrs added in v0.13.0

func (n *NativeNetwork) InterfaceMulticastAddrs() ([]net.Addr, error)

InterfaceMulticastAddrs returns the multicast addresses associated with the system. This method delegates to each native interface's MulticastAddrs method.

func (*NativeNetwork) Interfaces added in v0.13.0

func (n *NativeNetwork) Interfaces() ([]NetworkInterface, error)

Interfaces returns all network interfaces available on the system. This method delegates to net.Interfaces.

func (*NativeNetwork) InterfacesByIndex added in v0.13.0

func (n *NativeNetwork) InterfacesByIndex(
	index int,
) ([]NetworkInterface, error)

InterfacesByIndex returns the network interface with the given index. This method delegates to net.InterfaceByIndex.

func (*NativeNetwork) InterfacesByName added in v0.13.0

func (n *NativeNetwork) InterfacesByName(
	name string,
) ([]NetworkInterface, error)

InterfacesByName returns the network interface with the given name. This method delegates to net.InterfaceByName.

func (*NativeNetwork) IsNative added in v0.13.0

func (n *NativeNetwork) IsNative() bool

func (*NativeNetwork) Listen added in v0.13.0

func (n *NativeNetwork) Listen(
	ctx context.Context,
	network, address string,
) (net.Listener, error)

Listen announces on the specified network and address. It resolves the address, applies filtering, and creates a listener.

func (*NativeNetwork) ListenMulticastUDP added in v0.13.0

func (n *NativeNetwork) ListenMulticastUDP(
	ctx context.Context,
	network, address string,
	opts MulticastOptions,
) (MulticastPacketConn, error)

func (*NativeNetwork) ListenPacket added in v0.13.0

func (n *NativeNetwork) ListenPacket(
	ctx context.Context,
	network, address string,
) (PacketConn, error)

ListenPacket announces on the specified network and address for packet-oriented protocols. It resolves the address, applies filtering, and creates a packet connection.

func (*NativeNetwork) ListenPacketConfig added in v0.13.0

func (n *NativeNetwork) ListenPacketConfig(
	ctx context.Context,
	lc *ListenConfig,
	network, address string,
) (PacketConn, error)

ListenPacketConfig announces on the specified network and address for packet-oriented protocols using the provided listen configuration. It resolves the address, applies filtering, and creates a packet connection.

func (*NativeNetwork) ListenTCP added in v0.13.0

func (n *NativeNetwork) ListenTCP(
	ctx context.Context,
	network, laddr string,
) (TCPListener, error)

ListenTCP announces on the specified network and address for TCP connections. It resolves the address, applies filtering, and creates a TCP listener.

func (*NativeNetwork) ListenUDP added in v0.13.0

func (n *NativeNetwork) ListenUDP(
	ctx context.Context,
	network, laddr string,
) (UDPConn, error)

ListenUDP announces on the specified network and address for UDP connections. It resolves the address, applies filtering, and creates a UDP connection.

func (*NativeNetwork) ListenUDPConfig added in v0.13.0

func (n *NativeNetwork) ListenUDPConfig(
	ctx context.Context,
	lc *ListenConfig,
	network, laddr string,
) (UDPConn, error)

ListenUDPConfig announces on the specified network and address for UDP connections using the provided listen configuration. Since net.ListenConfig does not expose ListenUDP, this is implemented via ListenPacket and narrowed back to UDPConn.

func (*NativeNetwork) LookupAddr added in v0.13.0

func (n *NativeNetwork) LookupAddr(
	ctx context.Context,
	addr string,
) ([]string, error)

LookupAddr performs a reverse lookup for the given address, returning a slice of names mapping to that address. This method applies filtering before performing the lookup.

func (*NativeNetwork) LookupCNAME added in v0.13.0

func (n *NativeNetwork) LookupCNAME(
	ctx context.Context,
	host string,
) (string, error)

LookupCNAME returns the canonical name for the given host. This method applies filtering before performing the lookup.

func (*NativeNetwork) LookupHost added in v0.13.0

func (n *NativeNetwork) LookupHost(
	ctx context.Context,
	host string,
) ([]string, error)

LookupHost looks up the host and returns a slice of IP address strings. This method applies filtering before performing the lookup.

func (*NativeNetwork) LookupIP added in v0.13.0

func (n *NativeNetwork) LookupIP(
	ctx context.Context,
	network, address string,
) ([]net.IP, error)

LookupIP looks up the host and returns a slice of its IPv4 and IPv6 addresses. The network parameter specifies the network type ("ip", "ip4", or "ip6"). This method applies filtering before performing the lookup.

func (*NativeNetwork) LookupIPAddr added in v0.13.0

func (n *NativeNetwork) LookupIPAddr(
	ctx context.Context,
	host string,
) ([]net.IPAddr, error)

LookupIPAddr looks up the host and returns a slice of IPAddr structures. This method applies filtering before performing the lookup.

func (*NativeNetwork) LookupMX added in v0.13.0

func (n *NativeNetwork) LookupMX(
	ctx context.Context,
	name string,
) ([]*net.MX, error)

LookupMX returns the DNS MX records for the given domain name, sorted by preference. This method applies filtering before performing the lookup.

func (*NativeNetwork) LookupNS added in v0.13.0

func (n *NativeNetwork) LookupNS(
	ctx context.Context,
	name string,
) ([]*net.NS, error)

LookupNS returns the DNS NS records for the given domain name. This method applies filtering before performing the lookup.

func (*NativeNetwork) LookupNetAddr added in v0.13.0

func (n *NativeNetwork) LookupNetAddr(
	ctx context.Context,
	network, addr string,
) (net.IP, int, error)

LookupNetAddr resolves a network address string (e.g., "localhost:8080") into an IP address and port number. The network parameter specifies the network type (e.g., "tcp4", "udp6", "tcp"). This method applies filtering before performing the resolution.

func (*NativeNetwork) LookupNetIP added in v0.13.0

func (n *NativeNetwork) LookupNetIP(
	ctx context.Context,
	network, host string,
) ([]netip.Addr, error)

LookupNetIP looks up the host and returns a slice of netip.Addr values. The network parameter specifies the network type ("ip", "ip4", or "ip6"). This method applies filtering before performing the lookup.

func (*NativeNetwork) LookupPort added in v0.13.0

func (n *NativeNetwork) LookupPort(
	ctx context.Context,
	network, service string,
) (int, error)

LookupPort looks up the port number for the given network and service. This method applies filtering before performing the lookup.

func (*NativeNetwork) LookupSRV added in v0.13.0

func (n *NativeNetwork) LookupSRV(
	ctx context.Context,
	service, proto, name string,
) (string, []*net.SRV, error)

LookupSRV tries to resolve an SRV query for the given service, protocol, and domain name. The proto parameter is "tcp" or "udp". Returns the canonical host name and a slice of SRV records. This method applies filtering before performing the lookup.

func (*NativeNetwork) LookupTXT added in v0.13.0

func (n *NativeNetwork) LookupTXT(
	ctx context.Context,
	name string,
) ([]string, error)

LookupTXT returns the DNS TXT records for the given domain name. This method applies filtering before performing the lookup.

func (*NativeNetwork) PacketDial added in v0.13.0

func (n *NativeNetwork) PacketDial(
	ctx context.Context, network, address string,
) (PacketConn, error)

PacketDial establishes a UDP connection to the remote address using the specified network.

type NetAddr added in v0.13.0

type NetAddr struct {
	Net  string
	Addr string
}

NetAddr is a simple implementation of net.Addr using a network string and address string.

func (*NetAddr) Network added in v0.13.0

func (na *NetAddr) Network() string

func (*NetAddr) String added in v0.13.0

func (na *NetAddr) String() string

type NetDefIface added in v0.13.0

type NetDefIface interface {
	Dial(
		ctx context.Context,
		network, address string,
	) (net.Conn, error)
	Interfaces() ([]NetworkInterface, error)
}

type NetTCPListener

type NetTCPListener struct {
	*net.TCPListener
}

func (*NetTCPListener) AcceptTCP

func (l *NetTCPListener) AcceptTCP() (TCPConn, error)

type Network

type Network interface {
	Resolver

	// IsNative reports whether Network instance provides direct access to
	// OS network stack or emulates it/adding mutation wrappers.
	// Simple Network middlewares like logging ones should preserve IsNative status
	// while complex ones (e.g. encrypting/proxyng/etc) should reports false.
	// Some Network consumers may directly run low-level optimised dial/listen
	// operations bypassing Network's methods calls if IsNative reports true.
	IsNative() bool

	Dial(
		ctx context.Context,
		network, address string,
	) (net.Conn, error)

	Listen(
		ctx context.Context,
		network, address string,
	) (net.Listener, error)

	PacketDial(ctx context.Context, network, address string) (PacketConn, error)

	ListenPacket(
		ctx context.Context,
		network, address string,
	) (PacketConn, error)

	DialTCP(
		ctx context.Context,
		network, laddr, raddr string,
	) (TCPConn, error)

	ListenTCP(
		ctx context.Context,
		network, laddr string,
	) (TCPListener, error)

	DialUDP(
		ctx context.Context,
		network, laddr, raddr string,
	) (UDPConn, error)

	ListenUDP(
		ctx context.Context,
		network, laddr string,
	) (UDPConn, error)

	ListenPacketConfig(
		ctx context.Context,
		lc *ListenConfig,
		network, address string,
	) (PacketConn, error)

	ListenUDPConfig(
		ctx context.Context,
		lc *ListenConfig,
		network, laddr string,
	) (UDPConn, error)

	ListenMulticastUDP(
		ctx context.Context,
		network, address string,
		opts MulticastOptions,
	) (MulticastPacketConn, error)

	// Interfaces returns the list of network interfaces known to this Network.
	// Implementations may return an empty slice when the network is virtual,
	// even though Dial/Listen/ListenPacket may still be usable. Multiple
	// entries with the same Index or Name are allowed.
	Interfaces() ([]NetworkInterface, error)
	// InterfaceAddrs returns the addresses associated with interfaces known
	// to this Network.
	// Implementations may return an empty slice when the network is virtual,
	// even though Dial/Listen/ListenPacket may still be usable.
	// Duplicates are allowed.
	InterfaceAddrs() ([]net.Addr, error)
	// InterfaceMulticastAddrs returns the multicast addresses associated with
	// interfaces known to this Network.
	// Implementations may return an empty slice when the network is virtual,
	// even though Dial/Listen/ListenPacket may still be usable.
	// Duplicates are allowed.
	InterfaceMulticastAddrs() ([]net.Addr, error)
	// InterfacesByIndex returns all interfaces that match the provided index.
	// Implementations may return an empty slice when the network is virtual,
	// even though Dial/Listen/ListenPacket may still be usable.
	// Multiple interfaces with the same index are allowed.
	InterfacesByIndex(index int) ([]NetworkInterface, error)
	// InterfacesByName returns all interfaces that match the provided name.
	// Implementations may return an empty slice when the network is virtual,
	// even though Dial/Listen/ListenPacket may still be usable.
	// Multiple interfaces with the same name are allowed.
	InterfacesByName(name string) ([]NetworkInterface, error)
}

Network defines an abstraction over network providers.

func DefaultNetwork added in v0.13.0

func DefaultNetwork(cfg *NativeConfig) Network

DefaultNetwork builds gonnect.NativeNetwork on compilation targets with native networking available (linux, windows, darwin, etc) and loopback network for others (wasm, etc). If cfg is nil, default one will be used. For loopback network cfg arg is ignored.

type NetworkInterface

type NetworkInterface interface {
	ID() string
	Index() int
	Name() string
	MTU() int
	HardwareAddr() net.HardwareAddr
	Flags() net.Flags
	Addrs() ([]net.Addr, error)
	MulticastAddrs() ([]net.Addr, error)
}

func DefaultInterface added in v0.13.0

func DefaultInterface(
	ctx context.Context,
	n NetDefIface,
) (NetworkInterface, error)

func WrapNativeInterfaces

func WrapNativeInterfaces(in []net.Interface) []NetworkInterface

type PacketConn

type PacketConn interface {
	net.PacketConn
	net.Conn
}

PacketConn is an interface for UDP-like packet connections.

func PacketConnWithCallbacks

func PacketConnWithCallbacks(c PacketConn, cb *Callbacks) PacketConn

PacketConnWithCallbacks wraps a PacketConn with callbacks, using the most specific wrapper type based on the underlying connection type.

type PacketDial

type PacketDial = func(ctx context.Context, network, address string) (PacketConn, error)

PacketDial is a function type for establishing UDP-like packet connections.

type PacketListen

type PacketListen = func(ctx context.Context, network, address string) (PacketConn, error)

PacketListen is a function type for creating UDP-like packet listeners.

type RejectNetwork added in v0.13.0

type RejectNetwork struct{}

RejectNetwork is a network implementation that rejects all operations with canonical errors. It implements gonnect.RejectNetwork.

func (*RejectNetwork) Dial added in v0.13.0

func (n *RejectNetwork) Dial(
	ctx context.Context,
	network, address string,
) (net.Conn, error)

Dial returns an appropriate error based on the network and address.

func (*RejectNetwork) DialTCP added in v0.13.0

func (n *RejectNetwork) DialTCP(
	ctx context.Context,
	network, laddr, raddr string,
) (TCPConn, error)

DialTCP returns an appropriate error based on the network and address.

func (*RejectNetwork) DialUDP added in v0.13.0

func (n *RejectNetwork) DialUDP(
	ctx context.Context,
	network, laddr, raddr string,
) (UDPConn, error)

DialUDP returns an appropriate error based on the network and address.

func (*RejectNetwork) InterfaceAddrs added in v0.13.0

func (n *RejectNetwork) InterfaceAddrs() ([]net.Addr, error)

InterfaceAddrs returns an empty slice and nil error.

func (*RejectNetwork) InterfaceMulticastAddrs added in v0.13.0

func (n *RejectNetwork) InterfaceMulticastAddrs() ([]net.Addr, error)

InterfaceMulticastAddrs returns an empty slice and nil error.

func (*RejectNetwork) Interfaces added in v0.13.0

func (n *RejectNetwork) Interfaces() ([]NetworkInterface, error)

Interfaces returns an empty slice and nil error.

func (*RejectNetwork) InterfacesByIndex added in v0.13.0

func (n *RejectNetwork) InterfacesByIndex(
	index int,
) ([]NetworkInterface, error)

InterfacesByIndex returns an empty slice and "interface not found" error.

func (*RejectNetwork) InterfacesByName added in v0.13.0

func (n *RejectNetwork) InterfacesByName(
	name string,
) ([]NetworkInterface, error)

InterfacesByName returns an empty slice and "interface not found" error.

func (*RejectNetwork) IsNative added in v0.13.0

func (n *RejectNetwork) IsNative() bool

func (*RejectNetwork) Listen added in v0.13.0

func (n *RejectNetwork) Listen(
	ctx context.Context,
	network, address string,
) (net.Listener, error)

Listen returns an appropriate error based on the network and address.

func (*RejectNetwork) ListenMulticastUDP added in v0.13.0

func (n *RejectNetwork) ListenMulticastUDP(
	ctx context.Context,
	network, address string,
	opts MulticastOptions,
) (MulticastPacketConn, error)

func (*RejectNetwork) ListenPacket added in v0.13.0

func (n *RejectNetwork) ListenPacket(
	ctx context.Context,
	network, address string,
) (PacketConn, error)

ListenPacket returns an appropriate error based on the network and address.

func (*RejectNetwork) ListenPacketConfig added in v0.13.0

func (n *RejectNetwork) ListenPacketConfig(
	ctx context.Context,
	lc *ListenConfig,
	network, address string,
) (PacketConn, error)

ListenPacketConfig returns an appropriate error based on the network and address.

func (*RejectNetwork) ListenTCP added in v0.13.0

func (n *RejectNetwork) ListenTCP(
	ctx context.Context,
	network, laddr string,
) (TCPListener, error)

ListenTCP returns an appropriate error based on the network and address.

func (*RejectNetwork) ListenUDP added in v0.13.0

func (n *RejectNetwork) ListenUDP(
	ctx context.Context,
	network, laddr string,
) (UDPConn, error)

ListenUDP returns an appropriate error based on the network and address.

func (*RejectNetwork) ListenUDPConfig added in v0.13.0

func (n *RejectNetwork) ListenUDPConfig(
	ctx context.Context,
	lc *ListenConfig,
	network, laddr string,
) (UDPConn, error)

ListenUDPConfig returns an appropriate error based on the network and address.

func (*RejectNetwork) LookupAddr added in v0.13.0

func (n *RejectNetwork) LookupAddr(
	ctx context.Context,
	addr string,
) ([]string, error)

LookupAddr returns a NoSuchHost error.

func (*RejectNetwork) LookupCNAME added in v0.13.0

func (n *RejectNetwork) LookupCNAME(
	ctx context.Context,
	host string,
) (string, error)

LookupCNAME returns a NoSuchHost error.

func (*RejectNetwork) LookupHost added in v0.13.0

func (n *RejectNetwork) LookupHost(
	ctx context.Context,
	host string,
) ([]string, error)

LookupHost returns a NoSuchHost error.

func (*RejectNetwork) LookupIP added in v0.13.0

func (n *RejectNetwork) LookupIP(
	ctx context.Context,
	network, address string,
) ([]net.IP, error)

LookupIP returns a NoSuchHost error.

func (*RejectNetwork) LookupIPAddr added in v0.13.0

func (n *RejectNetwork) LookupIPAddr(
	ctx context.Context,
	host string,
) ([]net.IPAddr, error)

LookupIPAddr returns a NoSuchHost error.

func (*RejectNetwork) LookupMX added in v0.13.0

func (n *RejectNetwork) LookupMX(
	ctx context.Context,
	name string,
) ([]*net.MX, error)

LookupMX returns a NoSuchHost error.

func (*RejectNetwork) LookupNS added in v0.13.0

func (n *RejectNetwork) LookupNS(
	ctx context.Context,
	name string,
) ([]*net.NS, error)

LookupNS returns a NoSuchHost error.

func (*RejectNetwork) LookupNetIP added in v0.13.0

func (n *RejectNetwork) LookupNetIP(
	ctx context.Context,
	network, host string,
) ([]netip.Addr, error)

LookupNetIP returns a NoSuchHost error.

func (*RejectNetwork) LookupPort added in v0.13.0

func (n *RejectNetwork) LookupPort(
	ctx context.Context,
	network, service string,
) (int, error)

LookupPort returns a NoSuchHost error for the service.

func (*RejectNetwork) LookupSRV added in v0.13.0

func (n *RejectNetwork) LookupSRV(
	ctx context.Context,
	service, proto, name string,
) (string, []*net.SRV, error)

LookupSRV returns a NoSuchHost error.

func (*RejectNetwork) LookupTXT added in v0.13.0

func (n *RejectNetwork) LookupTXT(
	ctx context.Context,
	name string,
) ([]string, error)

LookupTXT returns a NoSuchHost error.

func (*RejectNetwork) PacketDial added in v0.13.0

func (n *RejectNetwork) PacketDial(
	ctx context.Context, network, address string,
) (PacketConn, error)

PacketDial returns an appropriate error based on the network and address.

type Resolver

type Resolver interface {
	LookupIP(ctx context.Context, network, address string) ([]net.IP, error)

	LookupIPAddr(ctx context.Context, host string) ([]net.IPAddr, error)

	LookupNetIP(ctx context.Context, network, host string) ([]netip.Addr, error)

	LookupHost(ctx context.Context, host string) (addrs []string, err error)

	LookupAddr(ctx context.Context, addr string) (names []string, err error)

	LookupCNAME(ctx context.Context, host string) (cname string, err error)

	LookupPort(
		ctx context.Context,
		network, service string,
	) (port int, err error)

	LookupNS(ctx context.Context, name string) ([]*net.NS, error)

	LookupMX(
		ctx context.Context,
		name string,
	) ([]*net.MX, error)

	LookupSRV(
		ctx context.Context,
		service, proto, name string,
	) (string, []*net.SRV, error)

	LookupTXT(
		ctx context.Context,
		name string,
	) ([]string, error)
}

type ResolverCfg

type ResolverCfg struct {
	// DontPreferGo disables the use of Go's pure Go DNS resolver.
	// When false (default), PreferGo is enabled in the built resolver.
	DontPreferGo bool
	// StrictErrors controls whether errors from the DNS server are fatal.
	// When true, errors stop resolution immediately.
	StrictErrors bool
	// Dial is an optional custom dial function for establishing connections.
	// If nil, uses net.Dialer.DialContext.
	Dial Dial
	// Server is an optional custom DNS server to use for resolution.
	// If nil, uses the system default DNS servers.
	Server *DnsServer
}

ResolverCfg configures a DNS resolver.

func (ResolverCfg) Build

func (cfg ResolverCfg) Build() net.Resolver

Build creates and returns a configured net.Resolver instance. If Server is set, all DNS queries are routed through that server. If Dial is set, it is used for establishing connections instead of the default dialer.

type Router added in v0.14.0

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

Router is a Network implementation that routes frontend operations to one of sixteen replaceable backend Network instances.

Backends can be attached, detached, or replaced while the Router is in use. Detaching or replacing a backend closes all connections, listeners, accepted connections, and UDP backend sockets that were opened through that slot. Close and Down stop the Router itself, cancel pending operations, and close all objects returned by the Router.

A Router is operational only when it has not been forced down with Down and at least one attached backend slot is operational. Empty slots and attached UpDown backends that are down or closed do not keep the Router up. Attached backends that do not implement UpDown are treated as always operational. Backend shutdown can make the Router go down, but it does not close the Router; subscribed closers run only when the Router itself is closed.

UDP listeners are frontend objects owned by the Router. For every alive frontend UDP listener, the Router keeps one backend UDP listener per attached backend slot. Reads fan in packets from all backend sockets, while writes are routed per packet with RouterCfg.RouteUDP.

func NewRouter added in v0.14.0

func NewRouter() *Router

NewRouter creates an empty Router. Without a RouterCfg, operations route to slot 1.

func (*Router) Attach added in v0.14.0

func (r *Router) Attach(slot int, backend Network) error

Attach installs backend in slot. Slots are numbered 1 through 16. Attaching nil is equivalent to Detach. Replacing a backend closes every object opened through the previous backend in that slot.

func (*Router) Close added in v0.14.0

func (r *Router) Close() error

Close permanently closes this Router.

func (*Router) Detach added in v0.14.0

func (r *Router) Detach(slot int) error

Detach removes the backend in slot and closes every object opened through it.

func (*Router) Dial added in v0.14.0

func (r *Router) Dial(
	ctx context.Context,
	network, address string,
) (net.Conn, error)

func (*Router) DialTCP added in v0.14.0

func (r *Router) DialTCP(
	ctx context.Context,
	network, laddr, raddr string,
) (TCPConn, error)

func (*Router) DialUDP added in v0.14.0

func (r *Router) DialUDP(
	ctx context.Context,
	network, laddr, raddr string,
) (UDPConn, error)

func (*Router) Down added in v0.14.0

func (r *Router) Down() error

Down stops the Router, cancels pending operations, and closes all Router owned objects. It does not call Down or Close on attached backend Networks.

func (*Router) GetCfg added in v0.14.0

func (r *Router) GetCfg() RouterCfg

GetCfg returns the currently installed routing config.

func (*Router) GetResolver added in v0.14.0

func (r *Router) GetResolver() Resolver

GetResolver returns the currently installed optional resolver.

func (*Router) InterfaceAddrs added in v0.14.0

func (r *Router) InterfaceAddrs() ([]net.Addr, error)

func (*Router) InterfaceMulticastAddrs added in v0.14.0

func (r *Router) InterfaceMulticastAddrs() ([]net.Addr, error)

func (*Router) Interfaces added in v0.14.0

func (r *Router) Interfaces() ([]NetworkInterface, error)

func (*Router) InterfacesByIndex added in v0.14.0

func (r *Router) InterfacesByIndex(index int) ([]NetworkInterface, error)

func (*Router) InterfacesByName added in v0.14.0

func (r *Router) InterfacesByName(name string) ([]NetworkInterface, error)

func (*Router) IsNative added in v0.14.0

func (r *Router) IsNative() bool

IsNative always reports false. Router is a frontend over other Networks.

func (*Router) IsUp added in v0.14.0

func (r *Router) IsUp() (bool, error)

IsUp reports whether this Router is currently up.

func (*Router) Listen added in v0.14.0

func (r *Router) Listen(
	ctx context.Context,
	network, address string,
) (net.Listener, error)

func (*Router) ListenMulticastUDP added in v0.14.0

func (r *Router) ListenMulticastUDP(
	ctx context.Context,
	network, address string,
	opts MulticastOptions,
) (MulticastPacketConn, error)

func (*Router) ListenPacket added in v0.14.0

func (r *Router) ListenPacket(
	ctx context.Context,
	network, address string,
) (PacketConn, error)

func (*Router) ListenPacketConfig added in v0.14.0

func (r *Router) ListenPacketConfig(
	ctx context.Context,
	lc *ListenConfig,
	network, address string,
) (PacketConn, error)

func (*Router) ListenTCP added in v0.14.0

func (r *Router) ListenTCP(
	ctx context.Context,
	network, laddr string,
) (TCPListener, error)

func (*Router) ListenUDP added in v0.14.0

func (r *Router) ListenUDP(
	ctx context.Context,
	network, laddr string,
) (UDPConn, error)

func (*Router) ListenUDPConfig added in v0.14.0

func (r *Router) ListenUDPConfig(
	ctx context.Context,
	lc *ListenConfig,
	network, laddr string,
) (UDPConn, error)

func (*Router) LookupAddr added in v0.14.0

func (r *Router) LookupAddr(
	ctx context.Context,
	addr string,
) ([]string, error)

func (*Router) LookupCNAME added in v0.14.0

func (r *Router) LookupCNAME(ctx context.Context, host string) (string, error)

func (*Router) LookupHost added in v0.14.0

func (r *Router) LookupHost(
	ctx context.Context,
	host string,
) ([]string, error)

func (*Router) LookupIP added in v0.14.0

func (r *Router) LookupIP(
	ctx context.Context,
	network, address string,
) ([]net.IP, error)

func (*Router) LookupIPAddr added in v0.14.0

func (r *Router) LookupIPAddr(
	ctx context.Context,
	host string,
) ([]net.IPAddr, error)

func (*Router) LookupMX added in v0.14.0

func (r *Router) LookupMX(ctx context.Context, name string) ([]*net.MX, error)

func (*Router) LookupNS added in v0.14.0

func (r *Router) LookupNS(ctx context.Context, name string) ([]*net.NS, error)

func (*Router) LookupNetIP added in v0.14.0

func (r *Router) LookupNetIP(
	ctx context.Context,
	network, host string,
) ([]netip.Addr, error)

func (*Router) LookupPort added in v0.14.0

func (r *Router) LookupPort(
	ctx context.Context,
	network, service string,
) (int, error)

func (*Router) LookupSRV added in v0.14.0

func (r *Router) LookupSRV(
	ctx context.Context,
	service, proto, name string,
) (string, []*net.SRV, error)

func (*Router) LookupTXT added in v0.14.0

func (r *Router) LookupTXT(ctx context.Context, name string) ([]string, error)

func (*Router) PacketDial added in v0.14.0

func (r *Router) PacketDial(
	ctx context.Context,
	network, address string,
) (PacketConn, error)

func (*Router) SetCfg added in v0.14.0

func (r *Router) SetCfg(cfg RouterCfg)

SetCfg replaces the routing config. Passing nil restores default routing to slot 1.

func (*Router) SetResolver added in v0.14.0

func (r *Router) SetResolver(res Resolver)

SetResolver replaces the optional resolver used by this Router. Passing nil removes it. When set, all Lookup operations go directly to this resolver and Dial/Listen operations pre-resolve host and service names through it before slot selection.

func (*Router) SubscribeCloser added in v0.14.0

func (r *Router) SubscribeCloser(c io.Closer) (func(), error)

SubscribeCloser registers c to be closed when this Router is closed.

The returned unsubscribe function removes c without closing it. If the Router is already closed, c is closed before SubscribeCloser returns net.ErrClosed.

func (*Router) SubscribeUpDown added in v0.15.0

func (r *Router) SubscribeUpDown(u UpDown) (func(), error)

SubscribeUpDown registers u to follow this Router's up/down state.

The returned unsubscribe function removes u without changing it. The subscription persists across Down and Up cycles. If the Router is already down or closed, u.Down is called before SubscribeUpDown returns.

func (*Router) Up added in v0.14.0

func (r *Router) Up() error

Up re-enables a stopped Router. Backend attachments and RouterCfg are kept.

type RouterCfg added in v0.14.0

type RouterCfg interface {
	DialTCP(network, laddr, raddr string) (slot int)
	ListenTCP(network, laddr string) (slot int)
	DialUDP(network, laddr, raddr string) (slot int)
	RouteUDP(network string, laddr, raddr net.Addr) (slot int)
	Lookup(network, address string) (slot int)
}

RouterCfg selects the backend slot used for routed operations.

Slots are numbered from 1 through 16. Returning any other slot, or returning a slot without an attached backend, makes the Router fail the operation with the same canonical error a RejectNetwork would return for that operation.

type TCPConn

type TCPConn interface {
	// Read(b []byte) (n int, err error)
	// Write(b []byte) (n int, err error)
	// Close() error
	// LocalAddr() Addr
	// RemoteAddr() Addr
	// SetDeadline(t time.Time) error
	// SetReadDeadline(t time.Time) error
	// SetWriteDeadline(t time.Time) error
	net.Conn

	// ReadFrom(r io.Reader) (int64, error)
	io.ReaderFrom

	// WriteTo(w io.Writer) (int64, error)
	io.WriterTo

	SetKeepAlive(keepalive bool) error
	SetKeepAliveConfig(config net.KeepAliveConfig) error
	SetKeepAlivePeriod(d time.Duration) error
	SetLinger(sec int) error
	SetNoDelay(noDelay bool) error

	CloseRead() error
	CloseWrite() error
}

func PipeTCP added in v0.13.0

func PipeTCP() (client, server TCPConn)

PipeTCP creates a pair of connected loopbackTCPConn using a buffered in-memory full-duplex transport. The connections communicate directly through an in-memory pipe without using actual network sockets. Both connections have their local and remote addresses set to point to each other. This is analogous to net.Pipe() but includes per-direction buffering.

func TCPConnWithCallbacks added in v0.13.0

func TCPConnWithCallbacks(c TCPConn, cb *Callbacks) TCPConn

TCPConnWithCallbacks wraps a TCPConn with callbacks.

type TCPListener

type TCPListener interface {
	// Accept() (Conn, error)
	// Close() error
	// Addr() Addr
	net.Listener

	AcceptTCP() (TCPConn, error)
	SetDeadline(t time.Time) error
}

func TCPListenerWithCallbacks added in v0.13.0

func TCPListenerWithCallbacks(l TCPListener, cb *Callbacks) TCPListener

TCPListenerWithCallbacks wraps a TCPListener with callbacks.

type UDPConn

type UDPConn interface {
	// Read(b []byte) (n int, err error)
	// Write(b []byte) (n int, err error)
	// Close() error
	// LocalAddr() Addr
	// RemoteAddr() Addr
	// SetDeadline(t time.Time) error
	// SetReadDeadline(t time.Time) error
	// SetWriteDeadline(t time.Time) error
	net.Conn

	// ReadFrom(p []byte) (n int, addr Addr, err error)
	// WriteTo(p []byte, addr Addr) (n int, err error)
	net.PacketConn

	ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error)
	ReadFromUDPAddrPort(b []byte) (n int, addr netip.AddrPort, err error)

	WriteToUDP(b []byte, addr *net.UDPAddr) (int, error)
	WriteToUDPAddrPort(b []byte, addr netip.AddrPort) (int, error)

	ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *net.UDPAddr, err error)
	ReadMsgUDPAddrPort(
		b, oob []byte,
	) (n, oobn, flags int, addr netip.AddrPort, err error)

	WriteMsgUDP(b, oob []byte, addr *net.UDPAddr) (n, oobn int, err error)
	WriteMsgUDPAddrPort(
		b, oob []byte,
		addr netip.AddrPort,
	) (n, oobn int, err error)
}

func PipeUDP added in v0.13.0

func PipeUDP() (conn1, conn2 UDPConn)

PipeUDP creates a pair of connected loopbackUDPConn that communicate via buffered channels. The connections are set up to send packets to each other directly without using actual network sockets or registry lookup. This is analogous to net.Pipe() but for UDP-style packet communication.

func UDPConnWithCallbacks

func UDPConnWithCallbacks(c UDPConn, cb *Callbacks) UDPConn

UDPConnWithCallbacks wraps a UDPConn with callbacks, using the most specific wrapper type based on the underlying connection type.

type UpDown

type UpDown interface {
	// Up activates or brings the resource online.
	Up() error
	// Down deactivates or brings the resource offline.
	// All active connections/listeners/etc must be closed on down.
	Down() error

	IsUp() (bool, error)
}

UpDown defines an interface for managing the operational state of a resource.

type UpDownSubscriber added in v0.15.0

type UpDownSubscriber interface {
	SubscribeUpDown(u UpDown) (func(), error)
}

UpDownSubscriber is implemented by Network values that can attach external UpDown resources to their own operational state.

SubscribeUpDown registers u to be moved down when the Network goes down or is closed, and moved up when the Network goes up. The subscription persists across repeated Down and Up calls until the returned unsubscribe function is called. If the Network is already down or closed, u.Down is called before SubscribeUpDown returns.

Network implementations that also implement UpDown must implement UpDownSubscriber.

type Wrapper

type Wrapper interface {
	GetWrapped() any
}

Wrapper is an interface for types that wrap underlying values. Implementing types should return the wrapped value via GetWrapped.

Directories

Path Synopsis
Package dns provides a channel-based DNS message interface and adapters for composing DNS providers, consumers, and middleware.
Package dns provides a channel-based DNS message interface and adapters for composing DNS providers, consumers, and middleware.
Package sockopt provides platform-specific socket option manipulation.
Package sockopt provides platform-specific socket option manipulation.
Package subnet provides utilities for working with IP subnets, including well-known CIDR ranges, IP address arithmetic, and network manipulation.
Package subnet provides utilities for working with IP subnets, including well-known CIDR ranges, IP address arithmetic, and network manipulation.
Package testing implements helpers for gonnect interfaces implementations testing
Package testing implements helpers for gonnect interfaces implementations testing
Package tun provides a TUN (network tunnel) interface for handling virtual network devices.
Package tun provides a TUN (network tunnel) interface for handling virtual network devices.

Jump to

Keyboard shortcuts

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