pnet

package
v0.4.170 Latest Latest
Warning

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

Go to latest
Published: May 11, 2024 License: ISC Imports: 17 Imported by: 0

Documentation

Overview

Package pnet provides IP-related functions with few dependencies beyond the net package

Index

Constants

View Source
const (
	HardwareAddrMac48  = 6
	HardwareAddrEui64  = 8
	HardwareAddrInfini = 20
)
View Source
const (
	// tcp connection oriented
	//	- listener implementation is *net.TCPListener
	//	- network is tcp tcp4 tcp6
	//	- netListener.Addr implementation is *net.TCPAddr
	TransportTCP = iota + 1
	// udp connectionless
	TransportUDP
	// ip: no port: protocols like icmp
	TransportIP
	// Unix socket inside the kernel to a process on the same host
	TransportUnix
)
View Source
const Do46 = true
View Source
const (
	UseInterfaceNameCache = true
)

Variables

View Source
var DefaultRouteIPv4 = netip.MustParsePrefix("0.0.0.0/0")

DefaultRouteIPv4 is the default route “0/0” for IPv4

View Source
var DefaultRouteIPv6 = netip.MustParsePrefix("::/0")

DefaultRouteIPv6 is the default route “::/0” for IPv6

View Source
var ErrNoSuchInterface = func() (err error) {
	for _, e := net.InterfaceByName("a b"); e != nil; e = errors.Unwrap(e) {
		err = e
	}
	if err == nil {
		panic(perrors.NewPF("failed to obtain NoSuchInterface from InterfaceByName"))
	}
	return
}()

ErrNoSuchInterface is the value net.errNoSuchInterface

Usage:

if errors.Is(err, pnet.ErrNoSuchInterface) { …
View Source
var HardwareAddrLengthsWithZero = append([]int{0}, HardwareAddrLengths...)
View Source
var IPv4DefaultNetwork = netip.MustParsePrefix("0.0.0.0/0")
View Source
var IPv4VpnPrefix = netip.MustParsePrefix("0.0.0.0/1")
View Source
var IPv6DefaultNetwork = netip.MustParsePrefix("::/0")
View Source
var IPv6VpnPrefix = netip.MustParsePrefix("::/3")
View Source
var VPNRoute0IPv4 = netip.MustParsePrefix("0.0.0.0/1")

VPNRoute0IPv4 is overriding VPN route “0/1” for IPv4

View Source
var VPNRoute128IPv4 = netip.MustParsePrefix("128.0.0.0/1")

VPNRoute128IPv4 is overriding VPN route “128/1” for IPv4

View Source
var VPNRouteIPv6 = netip.MustParsePrefix("::/3")

VPNRouteIPv6 is overriding VPN route “::/3” for IPv6

Functions

func Addr46 added in v0.4.112

func Addr46(addr netip.Addr) (addr46 netip.Addr)

Addr46 converts 4in6 IPv6 addresses to IPv4 for consistent IPv4/IPv6

  • IPv6 has a special class of addresses represnting an IPv4 address
  • IPv6 “::ffff:192.0.2.128” represents the IPv4 address “192.0.2.128”
  • Addr46 converts such addresses to IPv4

func AddrPortFromAddr added in v0.4.153

func AddrPortFromAddr(addr net.Addr) (near netip.AddrPort, err error)

AddrPortFromAddr converts tcp-protocol string-based net.Addr to binary netip.AddrPort

func AddrPortToTCPAddr added in v0.4.87

func AddrPortToTCPAddr(addrPort netip.AddrPort) (addrInterface net.Addr)

AddrPortToTCPAddr: Network() "tcp"

func AddrPortToUDPAddr added in v0.4.87

func AddrPortToUDPAddr(addrPort netip.AddrPort) (addrInterface net.Addr)

AddrPortToUDPAddr: Network() "udp"

func AddrPortToUDPAddr2 added in v0.4.91

func AddrPortToUDPAddr2(addrPort netip.AddrPort) (addr *net.UDPAddr)

func AddrSlicetoPrefix added in v0.4.112

func AddrSlicetoPrefix(addrs []net.Addr, do46 bool) (prefixes []netip.Prefix, err error)

AddrSlicetoPrefix returns a netip.Prefix slice from an Addr slice

  • net.Interface.Addrs returns []net.Addr which is really []*net.IPNet
  • IPNet is cidr not address: netip.Prefix

func AddrToIPAddr added in v0.4.87

func AddrToIPAddr(addr netip.Addr) (addrInterface net.Addr)

AddrToIPAddr returns the net.Addr for an netip.Addr

func CachedName added in v0.4.88

func CachedName(ifIndex IfIndex) (name string)

func CheckRedirect

func CheckRedirect(req *http.Request, via []*http.Request) (err error)

func DumpHardwareAddr added in v0.4.86

func DumpHardwareAddr(a net.HardwareAddr) (s string)

func EnsureZone added in v0.4.86

func EnsureZone(addr netip.Addr, ifName string, ifIndex IfIndex, acceptNumeric ...bool) (addr2 netip.Addr, didChange, isNumeric bool, err error)

EnsureZone adds IPv6 zone as applicable

  • only non-global IPv6 should have zone
  • if acceptNumeric true no index to interface-name translation attempts take place. otherwise interface-name zone is preferred
  • a non-numeric zone is attempted from: addr, ifName
  • number cinversion to interfa e is attempted: addr, ifIndex
  • acceptNumeric true leaves an existing numeric zone

func Get

func Get(requestURL string, tlsConfig *tls.Config, ctx context.Context) (resp *http.Response, err error)

func HardwareAddrInterface added in v0.4.87

func HardwareAddrInterface(a net.HardwareAddr) (netInterface *net.Interface, isErrNoSuchInterface bool, err error)

func IPAddr

func IPAddr(IP net.IP, index IfIndex, zone string) (ipa *net.IPAddr, err error)

IPAddr returns IPAddr from IP and IfIndex to IPAddr

func IPNetString

func IPNetString(ipNet net.IPNet) (s string)

IPNetString is abbreviated form 0/0

func IPNetToPrefix added in v0.4.86

func IPNetToPrefix(netIPNet *net.IPNet, noIs4In6Translation ...bool) (prefix netip.Prefix, err error)

IPNetToPrefix returns the netip.Prefix that corresponds to older type net.IPNet

  • net.IPNet input is "1.2.3.4/24" or "fe80::1/64"
  • returned netip.Prefix values are valid
  • returned IPv6 addresses has blank Zone

func InterfaceAddrs added in v0.4.87

func InterfaceAddrs(netInterface *net.Interface) (i4, i6 []netip.Prefix, err error)

InterfaceAddrs gets Addresses for interface

  • netInterface.Name is interface name "eth0"
  • netInterface.Addr() returns assigned IP addresses

func InterfaceFromAddr added in v0.4.88

func InterfaceFromAddr(addr netip.Addr) (netInterface *net.Interface, prefix netip.Prefix, isNoSuchInterface bool, err error)

InterfaceFromAddr finds network interface and prefix for addr

  • returns interface and prefix or error
  • first uses Zone, then scans all interfaces for prefixes
  • addr must be valid

func InterfacePrefix added in v0.4.88

func InterfacePrefix(netInterface *net.Interface, addr netip.Addr) (prefix netip.Prefix, err error)

InterfacePrefix returns the network prefix assigned to netInterface that contains addr

  • if addr is not part of any prefix, returned prefix is invalid

func Interfaces added in v0.4.87

func Interfaces() (interfaces []net.Interface, err error)

func InvertMask

func InvertMask(IPMask net.IPMask) (out net.IPMask)

InvertMask inverts the bits of a mask the mask for 1.2.3.4/24 is normally ffffff00 or []byte{255, 255, 255, 0}

func IsBroadcast

func IsBroadcast(addr netip.Addr, IPMask net.IPMask) (isBroadcast bool)

IsBroadcast determines whether addr is the last address for Mask

  • the last address is typically broadcast
  • for 1.2.3.4/24 the network address 1.2.3.255 returns true

func IsDirect

func IsDirect(route netip.Prefix) bool

IsDirect determines if the route is direct

  • a direct route has mask 32 or 128 bit length /32 /128

func IsErrClosed added in v0.4.26

func IsErrClosed(err error) (isErrNetClosing bool)

IsErrClosed returns true if err is when waiting for accept and the socket is closed

  • can be used with net.Conn.Accept

func IsHardwareAddrLength added in v0.4.28

func IsHardwareAddrLength(byts []byte) (isHardwareAddrLength bool)

func IsIPv4

func IsIPv4(ip net.IP) (isIPv4 bool)

IsIPv4 determines if net.IP value is IPv4

func IsIPv6

func IsIPv6(ip net.IP) (isIPv6 bool)

IsIPv6 determines if net.IP value is IPv6

func IsNetwork

func IsNetwork(IP net.IP, IPMask net.IPMask) (isNetwork bool)

IsNetwork determines if IP is the network address (all zeros) for this Mask for 1.2.3.4/24 the network address 1.2.3.0 returns true

func IsNonGlobalIPv6 added in v0.4.86

func IsNonGlobalIPv6(addr netip.Addr) (needsZone bool)

IsNonGlobalIPv6 returns if addr is an IPv6 address that should have zone

func IsNzIP

func IsNzIP(ip net.IP) bool

IsNzIP is ip set and not zero

func IsZeros

func IsZeros(p net.IP) bool

IsZeros determines if every byte of the IP address is zero

func Listen added in v0.4.151

func Listen(
	network Network, addr string,
	cancel *atomic.Pointer[context.CancelFunc],
) (listener net.Listener, err error)

Listen obtains a tcp or other listener

  • network must be set. NetworkDefault yields “panic: listen: unknown network”
  • addr can be empty
  • default port is ephemeral, a high number like 59321
  • if IPv6 is allowed, default host typically becomes “::” not “::1”
  • limited to IPv4, eg. NetworkTCP4, default host typically becomes “0.0.0.0” not “127.0.0.1”

func MaskToBits added in v0.4.86

func MaskToBits(byts []byte) (bits int, err error)

MaskToBits returns number of leading 1-bits in byts

  • convert from net.IPMask to netip.Prefix

func NameCache added in v0.4.87

func NameCache() (m map[IfIndex]string)

func NetworkPrefixBitCount added in v0.4.29

func NetworkPrefixBitCount(byts []byte) (bits int)

func NewTLSConfig

func NewTLSConfig(cert *x509.Certificate) (tlsConfig *tls.Config)

func NewTransport

func NewTransport(tlsConfig *tls.Config) (httpTransport *http.Transport)

func Prefix46 added in v0.4.112

func Prefix46(prefix netip.Prefix) (prefix46 netip.Prefix)

func SetTestMap added in v0.4.90

func SetTestMap(testMap map[IfIndex]string, disableUpdate bool) (oldMap map[IfIndex]string)

func SplitAddrPort added in v0.4.87

func SplitAddrPort(addrPort netip.AddrPort) (IP net.IP, port int, zone string)

func UpdateNameCache added in v0.4.87

func UpdateNameCache() (err error)

func Zone added in v0.4.86

func Zone(addr netip.Addr) (zone string, znum int, hasZone, isNumeric bool)

Zone examines the zone included in addr

  • no zone: hasZone: false, isNumeric: false
  • numeric zone “1”: hasZone: true, isNumeric: true. Number is network interface index.
  • interface-name zone “eth0”: hasZone: true, isNumeric false

Types

type Action added in v0.4.86

type Action uint8

Action describes the message action

const (
	AddRoute        Action = iota + 1 // AddRoute describes a new route added to the routing table
	DeleteRoute                       // DeleteRoute describes a deleted route
	RouteReport                       // RouteReport describes an existing route
	Partition                         // Partition describes an existing route that may be overridden
	AddHost                           // AddHost is a host added to the routing table
	DeleteHost                        // DeleteHost is a deleted host
	HostReport                        // HostReport is an existing host
	IfAddAddr                         // IfAddAddr Add address to interface
	IfDeleteAddr                      // IfDeleteAddr Delete address from interface
	IfStatus                          // network-interface upDownStatus or down string
	AddMulticast                      // AddMulticast annouces a multicast address
	DeleteMulticast                   // DeleteMulticast annouces a multicast address disappearing
)

func (Action) Description added in v0.4.88

func (a Action) Description() (s string)

func (Action) IsValid added in v0.4.90

func (a Action) IsValid() (isValid bool)

func (Action) String added in v0.4.86

func (a Action) String() (s string)

type Callback

type Callback func(msg Message)

Callback allows for processing of routing message,eg. populating a map

type ConnectionReceiver added in v0.4.166

type ConnectionReceiver[C net.Conn] interface {
	// Handle operates on and closes a connection
	//	- may only be invoked once or panic
	//	- the provided connection is guaranteed to be closed
	//	- thread-safe
	//	- Handle invocations after Shutdown immediately
	//		close the connection
	Handle(conn C)
	// may be invoked at any time: before, after or in lieu of Handle
	//	- on Shutdown return, any provided connection has been
	//		closed and all resources have been released
	//	- thread-safe idempotent
	Shutdown()
	fmt.Stringer
}

ConnectionReceiver is used by ThreadSource to process or cancel connections

  • ThreadSource provides ahead notice so that any thread-strategy can be implemented
  • either Handle or Shutdown or both must be invoked for all obtained ConnectionReceivers

type Destination

type Destination struct {
	netip.Prefix
}

Destination represents a selector for routing, ie. an IPv4 or IPv6 address with zone and prefix. go1.18 introduced netip.Prefix for this purpose see Linux: ip route add. [ root PREFIX ] [ match PREFIX ] [ exact PREFIX ] [ table TABLE_ID ] [ vrf NAME ] [ proto RTPROTO ] [ type TYPE ] [ scope SCOPE ] contains IP, Zone and Mask

func NewDestination

func NewDestination(prefix netip.Prefix) (d *Destination)

NewDestination instantiates Destination. addr is IPv4 address or IPv6 address with Zone. prefix is number of bits actually used 0…32 for IPv4, 0…128 for IPv6

func (Destination) IsDefaultRoute added in v0.4.83

func (d Destination) IsDefaultRoute() (isDefault bool)

IsDefaultRoute returns whether Destination is a default route:

  • IPv4: 0/0 or 0.0.0.0/0
  • IPv6: ::

func (Destination) IsValid added in v0.4.86

func (d Destination) IsValid() (err error)

func (Destination) Key

func (d Destination) Key() (key netip.Prefix)

Key is a string suitable as a key in a map

func (Destination) String

func (d Destination) String() (s string)

"1.2.3.4/24" or "2000::/3" - abbreviate IPv4: "127.0.0.0/8" → "127/8" - IPv4 default route: "0.0.0.0/0" → "0/0"

  • IPv6 default route stays "::/0"

type HttpClient

type HttpClient struct {
	http.Client
}

func NewHttpClient

func NewHttpClient(tlsConfig *tls.Config) (httpClient *HttpClient)

func (*HttpClient) Get

func (ct *HttpClient) Get(requestURL string, ctx context.Context) (resp *http.Response, err error)

type IfIndex

type IfIndex uint32

IfIndex is a dynamic reference to a network interface on Linux systems

func NewIfIndex added in v0.4.28

func NewIfIndex(index uint32) (ifIndex IfIndex)

func NewIfIndexInt added in v0.4.86

func NewIfIndexInt(value int) (ifIndex IfIndex, err error)

func (IfIndex) Interface

func (ifIndex IfIndex) Interface() (netInterface *net.Interface, isErrNoSuchInterface bool, err error)

Interface gets net.Interface for ifIndex

  • netInterface.Name is interface name "eth0"
  • netInterface.Addr() returns assigned IP addresses

func (IfIndex) InterfaceAddrs added in v0.4.86

func (ifIndex IfIndex) InterfaceAddrs(useNameCache ...NameCacher) (name string, i4, i6 []netip.Prefix, err error)

InterfaceAddrs gets Addresses for interface

  • netInterface.Name is interface name "eth0"
  • netInterface.Addr() returns assigned IP addresses

func (IfIndex) InterfaceIndex added in v0.4.28

func (ifIndex IfIndex) InterfaceIndex() (interfaceIndex int)

Interface gets net.Interface for ifIndex

  • InterfaceIndex is unique for promting methods

func (IfIndex) IsValid added in v0.4.28

func (ifIndex IfIndex) IsValid() (isValid bool)

IsValid determines if interface index value is set, ie. > 0

func (IfIndex) String added in v0.4.28

func (ifIndex IfIndex) String() (s string)

"#13"

func (IfIndex) Zone

func (ifIndex IfIndex) Zone() (zone string, isNumeric bool, err error)

Zone gets net.IPAddr.Zone string for ifIndex

  • if an interfa ce name can be ontained, that is the zone
  • otherwise a numeric zone is used
  • if ifIndex is invalid, empty string

type InterfaceCache added in v0.4.87

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

InterfaceCache is a cache mapping per-boot stable network interface index #1 to name "lo0". Thread-Safe

func NewInterfaceCache added in v0.4.87

func NewInterfaceCache() (interfaceCache *InterfaceCache)

NewInterfaceCache returns a cache mapiing network-interfac eindex to name. Thread-Safe

func (*InterfaceCache) CachedName added in v0.4.87

func (i *InterfaceCache) CachedName(ifIndex IfIndex, noUpdate ...NameCacher) (name string, err error)

CachedName retrieves a name by index with optional cache update. Thread-Safe

  • default is to update
  • unknown index returns empty string

func (*InterfaceCache) CachedNameNoUpdate added in v0.4.87

func (i *InterfaceCache) CachedNameNoUpdate(ifIndex IfIndex) (name string)

CachedNameNoUpdate retrieves a name by index with no cache update. Thread-Safe

func (*InterfaceCache) Init added in v0.4.87

func (i *InterfaceCache) Init() (i0 *InterfaceCache)

Init loads the cache, an opeation that may fail. Funtional chaining. Thread-Safe

func (*InterfaceCache) Map added in v0.4.87

func (i *InterfaceCache) Map() (m map[IfIndex]string)

Map returns a copy of the current cache. Thread-Safe

func (*InterfaceCache) SetMap added in v0.4.90

func (i *InterfaceCache) SetMap(newMap map[IfIndex]string) (oldMap map[IfIndex]string)

Map replaces the cache. Thread-Safe

  • do not read from or write to newMap after SetMap

func (*InterfaceCache) Update added in v0.4.87

func (i *InterfaceCache) Update() (m map[IfIndex]string, err error)

Update updates the cache by reading all system interfaces. Thread-Safe

type LinkAddr

type LinkAddr struct {
	IfIndex                 // 0 is none
	Name             string // "" none
	net.HardwareAddr        // []byte
}

LinkAddr contains an Ethernet mac address, its interface name and interface index

func NewLinkAddr

func NewLinkAddr(index IfIndex, name string) (linkAddr *LinkAddr)

NewLinkAddr instantiates LinkAddr

func (*LinkAddr) Dump added in v0.4.86

func (a *LinkAddr) Dump() (s string)

func (*LinkAddr) Interface added in v0.4.87

func (a *LinkAddr) Interface() (netInterface *net.Interface, isNoSuchInterface bool, err error)

Interface returns net.Interface associated with LinkAddr

  • order is index, name, mac
  • if LinkAddr is zero-value, nil is returned

func (*LinkAddr) IsComplete added in v0.4.90

func (a *LinkAddr) IsComplete() (isComplete bool)

func (*LinkAddr) IsValid added in v0.4.86

func (a *LinkAddr) IsValid() (isValid bool)

func (*LinkAddr) IsZeroValue added in v0.4.86

func (a *LinkAddr) IsZeroValue() (isZeroValue bool)

func (*LinkAddr) NonZero added in v0.4.86

func (a *LinkAddr) NonZero() (s string)

"#13_en5_00:00:5e:00:53:01"

  • zero-values are skipped
  • zero-value: "zero-value"

func (*LinkAddr) OneString

func (a *LinkAddr) OneString() string

OneString picks the most meaningful value

  • interface name or hardware address or #interface index or "0"

func (*LinkAddr) SetHw added in v0.4.86

func (a *LinkAddr) SetHw(hw net.HardwareAddr) (err error)

func (*LinkAddr) SetName added in v0.4.90

func (a *LinkAddr) SetName(name string)

func (*LinkAddr) String

func (a *LinkAddr) String() (s string)

"en8(28)00:11:22:33:44:55:66"

func (*LinkAddr) UpdateFrom added in v0.4.90

func (a *LinkAddr) UpdateFrom(b *LinkAddr) (isComplete bool)

func (*LinkAddr) UpdateName

func (a *LinkAddr) UpdateName() (linkAddr *LinkAddr, err error)

UpdateName attempts to populate interface name if not already present

func (*LinkAddr) ZoneID

func (a *LinkAddr) ZoneID() string

ZoneID is the IPv6 ZoneID for this interface

type Message

type Message interface {
	Action() (action Action)
	Dump() (dump string)
	fmt.Stringer
}

Message is a portable routing message emitted by the netlink socket or obtain via sysctl

type NameCacher added in v0.4.90

type NameCacher uint8

NameCacher contaisn instructions for interface-name cache read: NoCache Update NoUpdate

const (
	NoCache  NameCacher = iota // name cache should not be used in the api call
	Update                     // use name cache and update the cache first
	NoUpdate                   // use name cache without update. Mechanic for ongoing name cache update is required
)

type Network added in v0.4.94

type Network string

the type of Network

  • NetworkTCP NetworkTCP4 NetworkTCP6
  • NetworkUDP NetworkUDP4 NetworkUDP6
  • NetworkIP NetworkIP4 NetworkIP6
  • NetworkUnix NetworkUnixGram NetworkUnixPacket
const (
	NetworkDefault    Network = ""           // default
	NetworkTCP        Network = "tcp"        // tcp IPv4 or IPv6
	NetworkTCP4       Network = "tcp4"       // net network tcp ipv4
	NetworkTCP6       Network = "tcp6"       // tcp IPv6
	NetworkUDP        Network = "udp"        // udp is udp IPv4 or IPv6
	NetworkUDP4       Network = "udp4"       // udp4 is udp IPv4
	NetworkUDP6       Network = "udp6"       // udp6 is udp IPv6
	NetworkIP         Network = "ip"         // ip is IP protocol IPv4 or IPv6 addressing
	NetworkIP4        Network = "ip4"        // ip4 is IP protocol IPv4
	NetworkIP6        Network = "ip6"        // ip6 is IP protocol IPv6
	NetworkUnix       Network = "unix"       // unix is tcp or udp over Unix socket
	NetworkUnixGram   Network = "unixgram"   // unixgram is udp over Unix socket
	NetworkUnixPacket Network = "unixpacket" // unixpacket is tcp over Unix socket
)

func ParseNetwork added in v0.4.151

func ParseNetwork(network string) (n Network, err error)

ParseNetwork checks if network is valid

  • tcp tcp4 tcp6 udp udp4 udp6 ip ip4 ip6 unix unixgram unixpacket

func (Network) IsValid added in v0.4.94

func (t Network) IsValid() (isValid bool)

func (Network) String added in v0.4.94

func (t Network) String() (s string)

type NextHop

type NextHop struct {
	/*
		if NextHop is an address on the local host or on a local subnet,
		Gateway is nil
		LinkAddr describes the local interface
		Src is the address on that local interface

		If Nexthop is remote, beyond any local subnet,
		Gateway is an IP on a local subnet
		LinkAddr describes the local interface for that subnet
		Src is the address on that local interface
	*/
	Gateway  netip.Addr
	LinkAddr            // LinkAddr is the hosts’s network interface where to send packets
	Src      netip.Addr // the source ip to use for originating packets on LinkAddr
	// contains filtered or unexported fields
}

NextHop describes a route target

func NewNextHop

func NewNextHop(gateway netip.Addr, linkAddr *LinkAddr, src netip.Addr) (nextHop *NextHop)

NewNextHop assembles a route destination

func NewNextHop2

func NewNextHop2(index IfIndex, gateway netip.Addr, src netip.Addr) (next *NextHop, err error)

NewNextHop2 assembles a route destination based on IfIndex

func NewNextHop3 added in v0.4.90

func NewNextHop3(gateway netip.Addr, linkAddr *LinkAddr, src netip.Addr, nIPv4, nIPv6 int) (nextHop *NextHop)

func NewNextHopCounts added in v0.4.28

func NewNextHopCounts(gateway netip.Addr, linkAddr *LinkAddr, src netip.Addr,
	useNameCache ...NameCacher,
) (nextHop *NextHop, err error)

NewNextHopCounts returns NextHop with current IP address counts

  • if input LinkAddr does not have interface name, interface name is added to output nextHop
  • 6in4 are converted to IPv4

func (*NextHop) Dump added in v0.4.86

func (n *NextHop) Dump() (s string)

func (*NextHop) HasGateway

func (n *NextHop) HasGateway() bool

HasGateway determines if next hop uses a remote gateway

func (*NextHop) HasSrc

func (n *NextHop) HasSrc() bool

HasSrc determines if next hop has src specified

func (*NextHop) IsZeroValue added in v0.4.86

func (n *NextHop) IsZeroValue() (isZeroValue bool)

func (*NextHop) Name added in v0.4.87

func (n *NextHop) Name(useNameCache ...NameCacher) (name string, err error)

Name returns nextHop interface name

  • name can be returned empty
  • name of Linkaddr, then interface from index, name, mac

func (*NextHop) String

func (n *NextHop) String() (s string)

func (*NextHop) Target

func (n *NextHop) Target() (gateway netip.Addr, s string)

Target describes the destination for this next hop

  • gateway is invalid for local network targets or gateway unspecified address "0.0.0.0"
  • s is:
  • empty string for nil NextHop
  • network interface name mac index or 0 for gateway missing, invalid or unspecified
  • otherwise gateway ip, interface description and source IP or source cidr

type Route

type Route struct {
	Destination
	NextHop
}

Route describes a routing table route with destination and next hop

func NewRoute

func NewRoute(d *Destination, nextHop *NextHop) *Route

NewRoute instantiates Route

func (*Route) Dump added in v0.4.86

func (r *Route) Dump() (s string)

func (*Route) String added in v0.4.28

func (r *Route) String() (s string)

type SocketListener added in v0.4.94

type SocketListener[C net.Conn] struct {
	// contains filtered or unexported fields
}

SocketListener is a generic wrapper for net.Listener

  • not intended for direct use, instead use specific implementations like:
  • TCPListener
  • C is the type of connection the handler function receives:
  • — net.Conn, *net.TCPConn, …
  • panic-handled connection threads
  • Ch: real-time error channel or collecting errors after close: Err
  • WaitCh: idempotent waitable thread-terminating Close
  • SocketListener methods are thread-safe

func NewSocketListener added in v0.4.94

func NewSocketListener[C net.Conn](
	listener net.Listener,
	network Network,
	transport SocketTransport,
) (socket *SocketListener[C])

NewSocketListener returns object listening for socket connections

  • C is the type of net.Listener the handler function provided to SocketListener.AcceptConnections
  • SocketListener provides asynchronous error handling
  • handler must invoke net.Conn.Close -
  • default threading is one virtual thread per connection
  • SocketListener.SetThreadSource allows for any thread model replacing handle

func (*SocketListener[C]) AcceptConnections added in v0.4.94

func (s *SocketListener[C]) AcceptConnections(handler func(C)) (goodClose bool)

AcceptConnections is a blocking function handling inbound connections

  • AcceptConnections can only be invoked once
  • handler must be non-nil or
  • socket state must be Listening
  • accepts connections until Close is invoked despite errors
  • handler must invoke net.Conn.Close

func (*SocketListener[C]) AddrPort added in v0.4.94

func (s *SocketListener[C]) AddrPort() (addrPort netip.AddrPort, err error)

func (*SocketListener[C]) Ch added in v0.4.94

func (s *SocketListener[C]) Ch() (ch <-chan error)

Ch returns a real-time error channel

  • the channel never closes
  • unread errors can also be collected using [TCPListener.Err]

func (*SocketListener[C]) Close added in v0.4.94

func (s *SocketListener[C]) Close() (err error)

Close ensures the socket is closed

  • socket guaranteed to be close on return
  • idempotent panic-free awaitable thread-safe

func (*SocketListener[C]) Err added in v0.4.94

func (s *SocketListener[C]) Err(errp *error)

Err returns all unread errors

  • errors can also be read using [TCPListener.Ch]

func (*SocketListener[C]) IsAccept added in v0.4.94

func (s *SocketListener[C]) IsAccept() (isAcceptThread bool)

IsAccept indicates whether the listener is functional and accepting incoming connections

func (*SocketListener[C]) Listen added in v0.4.94

func (s *SocketListener[C]) Listen(socketString string) (err error)

Listen binds listening to a near socket

  • socketString is host:port "1.2.3.4:80" "wikipedia.com:443" "/some/unix/socket"
  • — for TCP UDP IP host must resolve to an assigned near IP address
  • — — if host is blank, it is for localhost
  • — — to avoid DNS resolution host should be blank or literal IP address "1.2.3.4:0"
  • — for TCP UDP port must be literal port number 0…65534 where 0 means a temporary port
  • Listen can be repeatedly invoked until it succeeds

func (*SocketListener[C]) SetThreadSource added in v0.4.166

func (s *SocketListener[C]) SetThreadSource(threadSource ThreadSource[C])

func (*SocketListener[C]) WaitCh added in v0.4.94

func (s *SocketListener[C]) WaitCh() (closeWait chan struct{})

WaitCh returns a channel that closes when [] completes

  • ListenTCP4.Close needs to have been invoked for the channel to close

type SocketTransport added in v0.4.94

type SocketTransport uint8

SocketTransport describes what type of socket from the types supported by Go

  • TransportTCP TransportUDP TransportIP TransportUnix
  • 0 is uninitalized invalid

func (SocketTransport) IsValid added in v0.4.94

func (t SocketTransport) IsValid() (isValid bool)

IsValid returns true if the SocketTransport has been initialized

func (SocketTransport) String added in v0.4.94

func (t SocketTransport) String() (s string)

type TCPListener added in v0.4.62

type TCPListener struct {
	// the TCP IPv4 or IPv6 listening socket promoting TCP-specific methods
	*net.TCPListener
	// connection-handler argument is *net.TCPConn
	SocketListener[*net.TCPConn]
}

TCPListener wraps net.TCPListener

  • TCPListener provides:
  • — thread-safe methods from TCPListener and SocketListener
  • — promoted methods from net.TCPListener
  • — all errors via unbound error channel
  • — thread-safe state-handling for integrity
  • — idempotent panic-free awaitable thread-safe TCPListener.Close
  • — netip addresses
  • — panic-handled handler connection threads receiving *net.TCPConn
  • — awaitable Close and handler completion

func NewTCPListener added in v0.4.94

func NewTCPListener(network ...Network) (socket *TCPListener)

NewTCPListener returns an object for receiving tcp connections

Usage:

var socket = pnet.NewTCPListener()
if err = r.socket.Listen("1.2.3.4:1234"); err != nil {
	return // listen failed
}
defer parl.Close(&r.socket, &err)
println(socket.AddrPort().String()) // “127.0.0.1:1122”

func (*TCPListener) Close added in v0.4.93

func (s *TCPListener) Close() (err error)

- idempotent panic-free awaitable Close

type Tcp

type Tcp struct {
	net.Addr // interface
	http.ServeMux
	http.Server
	// contains filtered or unexported fields
}

type ThreadSource added in v0.4.166

type ThreadSource[C net.Conn] interface {
	// Receiver prepares the ThreadSource for a possible upcoming connection
	//	- done will be invoked exactly once by all connReceiver objects
	//	- to ensure done invocation, [ConnectionReceiver.Handle] or
	//		[ConnectionReceiver.Shutdown] or both must be invoked
	//	- Receiver and connReceiver.Handle do not block
	//	- any connection provided to [ConnectionReceiver.Handle] is
	//		guaranteed to be closed by Handle even if
	//		[ConnectionReceiver.Shutdown] was already invoked
	Receiver(done parl.Done, addError parl.AddError) (connReceiver ConnectionReceiver[C], err error)
}

ThreadSource provides a thread-allocation strategy

  • when Receiver is invoked, threads can be pre-launched for a pending connection
  • default allocation strategy when ThreadSource is not used is one thread per connection
  • ThreadSource allows for any thread-allocation strategy to be used when handling multiple connections
  • when connReceiver.Handle is invoked, threads launched by Receiver may already be waiting at a a lock for maximum performance

type UDP

type UDP struct {
	Network        string
	F              UDPFunc
	MaxSize        int
	net.UDPAddr    // struct IP Port Zone
	ListenInvoked  atomic.Bool
	StartingListen sync.WaitGroup
	ErrCh          chan<- error
	IsListening    atomic.Bool
	NetUDPConn     *net.UDPConn

	Addr       net.Addr
	IsShutdown atomic.Bool
	// contains filtered or unexported fields
}

func NewUDP

func NewUDP(network, address string, udpFunc UDPFunc, maxSize int) (udp *UDP)

NewUDP network: "udp" "udp4" "udp6" address: "host:port"

func (*UDP) Listen

func (udp *UDP) Listen() (errCh <-chan error)

func (*UDP) Shutdown

func (udp *UDP) Shutdown()

func (*UDP) WaitForUp

func (udp *UDP) WaitForUp() (isUp bool, addr net.Addr)

type UDPFunc

type UDPFunc func(b []byte, oob []byte, flags int, addr *net.UDPAddr)

Jump to

Keyboard shortcuts

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