Help us shape the future of Go! Take the 2026 Go Developer Survey

netutil

package
v1.3.104-alpha1 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2026 License: AGPL-3.0 Imports: 18 Imported by: 0

Documentation

Overview

Package netutil pkg/netutil/copy.go c0-com-util

Package netutil pkg/netutil/net.go c0-com-util

The TinyGo-safe (pure) helpers. Network-interface enumeration + the ipinfo.io HTTP probe live in net_native.go (//go:build !tinygo); their TinyGo stubs are in net_tinygo.go.

Package netutil pkg/netutil/net_linux.go c0-com-util

Package netutil pkg/netutil/net_native.go c0-com-util

Network-interface enumeration + the ipinfo.io HTTP probe. Split out of net.go behind //go:build !tinygo because TinyGo's net.Interface has no Addrs() method and net/http doesn't compile on the TinyGo wasm (js) target. A TinyGo dmsg client needs none of these (it has no host NICs to enumerate); the stubs in net_tinygo.go satisfy any transitive linker reference. See docs/design/tinygo-dmsg-client.md.

Package netutil pkg/netutil/policy.go c0-com-util

Package netutil pkg/netutil/porter.go c0-com-util

Package netutil pkg/netutil/retrier.go c0-com-util

Index

Constants

View Source
const (
	DefaultInitBackoff = time.Second
	DefaultMaxBackoff  = time.Second * 20
	DefaultTries       = int64(0)
	DefaultFactor      = float64(1.3)
)

Default values for retrier.

View Source
const (
	// PorterMinEphemeral is the default minimum ephemeral port.
	PorterMinEphemeral = uint16(49152)
)

Variables

View Source
var ErrEphemeralPortSpace = errors.New("ephemeral port space exhausted")

ErrEphemeralPortSpace is returned when no ephemeral ports are available.

View Source
var (
	ErrMaximumRetriesReached = errors.New("maximum retries attempted without success")
)

Package errors

Functions

func CopyReadWriteCloser

func CopyReadWriteCloser(conn1, conn2 io.ReadWriteCloser) error

CopyReadWriteCloser copies reads and writes between two connections. It returns when either direction encounters an error (including idle timeout).

func DefaultNetworkInterface

func DefaultNetworkInterface() (string, error)

DefaultNetworkInterface fetches default network interface name: the interface of each IPv4 default route, one a line, as `ip r` lists them.

Where the routing table cannot be read, as by an Android app, it is the interface the kernel routes a packet to the internet through, then the first usable interface. When none qualifies (airplane mode) it returns "" without error, which callers handle as unknown.

func DefaultNetworkInterfaceIPs

func DefaultNetworkInterfaceIPs() ([]net.IP, error)

DefaultNetworkInterfaceIPs returns IP addresses for the default network interface

func ExtractPort

func ExtractPort(addr net.Addr) (uint16, error)

ExtractPort returns port of the given UDP or TCP address

func HasPublicIP

func HasPublicIP() (bool, error)

HasPublicIP returns true if this machine has at least one publically available IP address

func IsAdvertisableIP

func IsAdvertisableIP(ip net.IP) bool

IsAdvertisableIP reports whether ip may be offered to peers as a local address: not loopback, not link-local, and not a CLAT address.

func IsPublicIP

func IsPublicIP(IP net.IP) bool

IsPublicIP returns true if the provided IP is public. Obtained from: https://stackoverflow.com/questions/41670155/get-public-ip-in-golang

func IsVirtualInterface

func IsVirtualInterface(name string) bool

IsVirtualInterface reports whether name is an interface whose addresses must not be advertised to peers (see virtualIfacePrefixes).

func LocalAddresses

func LocalAddresses() ([]string, error)

LocalAddresses returns the addresses the visor may offer peers: global unicast, on an up interface that is not virtual, and permitted by the advertise policy (see SetAdvertisePolicy).

func LocalAddressesDetail

func LocalAddressesDetail() (kept, excluded []string, err error)

LocalAddressesDetail is LocalAddresses plus what the advertise policy removed, each as "address (interface)".

func LocalNetworkInterfaceIPs

func LocalNetworkInterfaceIPs() ([]net.IP, error)

LocalNetworkInterfaceIPs gets IPs of all local interfaces.

func LocalProtocol

func LocalProtocol() bool

LocalProtocol check a condition to use dmsghttp or direct url

func MatchPolicyEntry

func MatchPolicyEntry(entry, ifname string, ip net.IP) bool

MatchPolicyEntry reports whether entry names the interface or holds the address. A nil ip or an empty name matches only the other kind.

func NetworkInterfaceIPs

func NetworkInterfaceIPs(name string) ([]net.IP, error)

NetworkInterfaceIPs gets IPs of network interface with name `name`.

func PolicyPermitsIP

func PolicyPermitsIP(ip net.IP) bool

PolicyPermitsIP reports whether the advertise policy lets ip be offered, looking up the interface that holds it.

func RouteSourceIPs

func RouteSourceIPs() (v4, v6 string)

RouteSourceIPs returns the local addresses the kernel would send internet traffic from, per family, or "" for a family with no route. Connecting a UDP socket looks the route up and sends nothing.

func SetAdvertisePolicy

func SetAdvertisePolicy(p AddrPolicy)

SetAdvertisePolicy installs the policy LocalAddresses and the WebRTC ICE filter apply. It is process wide, like the interfaces it filters.

func ValidatePolicyEntry

func ValidatePolicyEntry(e string) error

ValidatePolicyEntry checks one allow, deny or metered entry.

Types

type AddrPolicy

type AddrPolicy struct {
	Allow []string `json:"allow,omitempty"`
	Deny  []string `json:"deny,omitempty"`
}

AddrPolicy decides which local interfaces and addresses the visor offers to peers. An entry is an interface name glob ("wlan*", "eth0") or an address range ("10.0.0.0/8", "192.168.1.5"). Deny wins over allow, and an empty allow list allows everything.

func AdvertisePolicy

func AdvertisePolicy() AddrPolicy

AdvertisePolicy returns the policy in force, the zero policy by default.

func (AddrPolicy) AllowsNamed

func (p AddrPolicy) AllowsNamed(ifname string) bool

AllowsNamed reports whether an allow entry names ifname as an interface. Such an entry brings back an interface the virtual filter would drop.

func (AddrPolicy) DeniesInterface

func (p AddrPolicy) DeniesInterface(ifname string) bool

DeniesInterface reports whether a deny glob names ifname, so no address on it can be offered whatever the address is.

func (AddrPolicy) IsZero

func (p AddrPolicy) IsZero() bool

IsZero reports whether the policy allows every address.

func (AddrPolicy) Permits

func (p AddrPolicy) Permits(ifname string, ip net.IP) bool

Permits reports whether the address ip on interface ifname may be offered.

func (AddrPolicy) Validate

func (p AddrPolicy) Validate() error

Validate rejects an entry that is neither a valid glob nor an address range.

type EphemeralDiagEntry

type EphemeralDiagEntry struct {
	Port      uint16 `json:"port"`
	ValueType string `json:"value_type"` // e.g. "*dmsg.Stream", "<nil>"
	ValueInfo string `json:"value_info,omitempty"`
	Children  int    `json:"children,omitempty"`
}

EphemeralDiag returns diagnostic information about ephemeral port reservations. For each ephemeral port, it reports whether the stored value is nil, its type, and (for Stringer values) a short string representation. This helps identify what is holding ephemeral ports when the porter approaches exhaustion.

type EphemeralDiagResult

type EphemeralDiagResult struct {
	Total         int                  `json:"total"`
	Ephemeral     int                  `json:"ephemeral"`
	Listeners     int                  `json:"listeners"`
	NilValues     int                  `json:"nil_values"`
	TotalReserved uint64               `json:"total_reserved"` // monotonic counter
	TotalFreed    uint64               `json:"total_freed"`    // monotonic counter
	LeakRate      string               `json:"leak_rate"`      // current - freed as percentage
	TypeCount     map[string]int       `json:"type_count"`
	AgeBucket     map[string]int       `json:"age_bucket"`             // "0-30s", "30s-2m", "2m-5m", "5m-30m", "30m+"
	CallerCount   map[string]int       `json:"caller_count,omitempty"` // caller file:line → count (for entries >2min)
	Sample        []EphemeralDiagEntry `json:"sample,omitempty"`       // first 20 entries
}

type IfaceAddr

type IfaceAddr struct {
	Name string
	IP   net.IP
}

IfaceAddr is one address and the interface holding it.

func RouteInterfaces

func RouteInterfaces() []IfaceAddr

RouteInterfaces returns the interfaces and addresses the kernel would send internet traffic from, one per family that has a route.

type Porter

type Porter struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

Porter reserves ports.

func NewPorter

func NewPorter(minEph uint16) *Porter

NewPorter creates a new Porter with a given minimum ephemeral port value.

func (*Porter) CloseAll

func (p *Porter) CloseAll(log logrus.FieldLogger)

CloseAll closes all contained variables that implement io.Closer

func (*Porter) Count

func (p *Porter) Count() int

Count returns the number of currently reserved ports.

func (*Porter) EphemeralDiag

func (p *Porter) EphemeralDiag() EphemeralDiagResult

func (*Porter) PortValue

func (p *Porter) PortValue(port uint16) (interface{}, bool)

PortValue returns the value stored under a given port.

func (*Porter) RangePortValues

func (p *Porter) RangePortValues(fn func(port uint16, v interface{}) (next bool))

RangePortValues ranges all ports that are currently reserved.

func (*Porter) RangePortValuesAndChildren

func (p *Porter) RangePortValuesAndChildren(fn func(port uint16, v PorterValue) (next bool))

RangePortValuesAndChildren ranges port values and it's contained children.

func (*Porter) Reserve

func (p *Porter) Reserve(port uint16, v interface{}) (bool, func())

Reserve a given port. It returns a boolean informing whether the port is reserved, and a function to clear the reservation.

func (*Porter) ReserveChild

func (p *Porter) ReserveChild(port, subPort uint16, v interface{}) (bool, func())

ReserveChild reserves a child.

func (*Porter) ReserveEphemeral

func (p *Porter) ReserveEphemeral(ctx context.Context, v interface{}) (uint16, func(), error)

ReserveEphemeral reserves a new ephemeral port. It returns the reserved ephemeral port, a function to clear the reservation and an error (if any). Returns ErrEphemeralPortSpace if all ephemeral ports (minEph through 65535) are occupied.

func (*Porter) ResetEphemeral

func (p *Porter) ResetEphemeral() int

ResetEphemeral removes all ephemeral port reservations (ports >= minEph), freeing the port space. Well-known ports (listeners) are preserved. Use this to recover from ephemeral port exhaustion without restarting.

func (*Porter) SweepStaleEphemeral

func (p *Porter) SweepStaleEphemeral(maxAge time.Duration) int

SweepStaleEphemeral closes and frees ephemeral port entries older than maxAge. It calls Close() on entries whose Value implements io.Closer, then deletes the porter entry. Returns the number of entries swept.

This is a safety net for the DMSG stream lifecycle: if the normal cleanup paths (Stream.Read auto-release, explicit Close, session reaping) miss an entry, the sweeper catches it before the 16K port space is exhausted.

type PorterValue

type PorterValue struct {
	Value    interface{}
	Children map[uint16]interface{}
}

PorterValue associates a port value alongside it's children.

type Retrier

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

Retrier holds a configuration for how retries should be performed

func NewDefaultRetrier

func NewDefaultRetrier(log logrus.FieldLogger) *Retrier

NewDefaultRetrier creates a retrier with default values.

func NewRetrier

func NewRetrier(log logrus.FieldLogger, initBO, maxBO time.Duration, tries int64, factor float64) *Retrier

NewRetrier returns a retrier that is ready to call Do() method

func (*Retrier) Do

func (r *Retrier) Do(ctx context.Context, f RetryFunc) error

Do takes a RetryFunc and attempts to execute it. If it fails with an error it will be retried a maximum of given times with an initBO until it returns nil or an error that is whitelisted

func (*Retrier) WithErrWhitelist

func (r *Retrier) WithErrWhitelist(errors ...error) *Retrier

WithErrWhitelist sets a list of errors into the retrier, if the RetryFunc provided to Do() fails with one of them it will return inmediatelly with such error. Calling this function is not thread-safe, and is advised to only use it when initializing the Retrier

type RetryFunc

type RetryFunc func() error

RetryFunc is a function used as argument of (*Retrier).Do(), which will retry on error unless it is whitelisted

Jump to

Keyboard shortcuts

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