Documentation
¶
Overview ¶
Package pnet provides IP-related functions with few dependencies beyond the net package
Index ¶
- Constants
- Variables
- func Addr46(addr netip.Addr) (addr46 netip.Addr)
- func AddrPortFromAddr(addr net.Addr) (near netip.AddrPort, err error)
- func AddrPortToTCPAddr(addrPort netip.AddrPort) (addrInterface net.Addr)
- func AddrPortToUDPAddr(addrPort netip.AddrPort) (addrInterface net.Addr)
- func AddrPortToUDPAddr2(addrPort netip.AddrPort) (addr *net.UDPAddr)
- func AddrSlicetoPrefix(addrs []net.Addr, do46 bool) (prefixes []netip.Prefix, err error)
- func AddrToIPAddr(addr netip.Addr) (addrInterface net.Addr)
- func CachedName(ifIndex IfIndex) (name string)
- func DumpHardwareAddr(a net.HardwareAddr) (s string)
- func EnsureZone(addr netip.Addr, ifName string, ifIndex IfIndex, acceptNumeric ...bool) (addr2 netip.Addr, didChange, isNumeric bool, err error)
- func HardwareAddrInterface(a net.HardwareAddr) (netInterface *net.Interface, isErrNoSuchInterface bool, err error)
- func IPAddr(IP net.IP, index IfIndex, zone string) (ipa *net.IPAddr, err error)
- func IPNetString(ipNet net.IPNet) (s string)
- func IPNetToPrefix(netIPNet *net.IPNet, noIs4In6Translation ...bool) (prefix netip.Prefix, err error)
- func InterfaceAddrs(netInterface *net.Interface) (i4, i6 []netip.Prefix, err error)
- func InterfaceFromAddr(addr netip.Addr) (netInterface *net.Interface, prefix netip.Prefix, isNoSuchInterface bool, ...)
- func InterfacePrefix(netInterface *net.Interface, addr netip.Addr) (prefix netip.Prefix, err error)
- func Interfaces() (interfaces []net.Interface, err error)
- func InvertMask(IPMask net.IPMask) (out net.IPMask)
- func IsBroadcast(addr netip.Addr, IPMask net.IPMask) (isBroadcast bool)
- func IsDirect(route netip.Prefix) bool
- func IsErrClosed(err error) (isErrNetClosing bool)
- func IsHardwareAddrLength(byts []byte) (isHardwareAddrLength bool)
- func IsIPv4(ip net.IP) (isIPv4 bool)
- func IsIPv6(ip net.IP) (isIPv6 bool)
- func IsNetwork(IP net.IP, IPMask net.IPMask) (isNetwork bool)
- func IsNonGlobalIPv6(addr netip.Addr) (needsZone bool)
- func IsNzIP(ip net.IP) bool
- func IsZeros(p net.IP) bool
- func Listen(socketAddress SocketAddress, cancel ...*atomic.Pointer[context.CancelFunc]) (listener net.Listener, err error)
- func MaskToBits(byts []byte) (bits int, err error)
- func NetworkPrefixBitCount(byts []byte) (bits int)
- func NewTLSConfig(cert *x509.Certificate) (tlsConfig *tls.Config)
- func Prefix46(prefix netip.Prefix) (prefix46 netip.Prefix)
- func SetTestMap(testMap map[IfIndex]string, disableUpdate bool) (oldMap map[IfIndex]string)
- func SplitAddrPort(addrPort netip.AddrPort) (IP net.IP, port int, zone string)
- func UpdateNameCache() (err error)
- func Zone(addr netip.Addr) (zone string, znum int, hasZone, isNumeric bool)
- type Action
- type AddrPort
- type Address
- type Callback
- type ConnectionReceiver
- type Destination
- type IfIndex
- func (ifIndex IfIndex) Interface() (netInterface *net.Interface, isErrNoSuchInterface bool, err error)
- func (ifIndex IfIndex) InterfaceAddrs(useNameCache ...NameCacher) (name string, i4, i6 []netip.Prefix, err error)
- func (ifIndex IfIndex) InterfaceIndex() (interfaceIndex int)
- func (ifIndex IfIndex) IsValid() (isValid bool)
- func (ifIndex IfIndex) String() (s string)
- func (ifIndex IfIndex) Zone() (zone string, isNumeric bool, err error)
- type InterfaceCache
- type LinkAddr
- func (a *LinkAddr) Dump() (s string)
- func (a *LinkAddr) Interface() (netInterface *net.Interface, isNoSuchInterface bool, err error)
- func (a *LinkAddr) IsComplete() (isComplete bool)
- func (a *LinkAddr) IsValid() (isValid bool)
- func (a *LinkAddr) IsZeroValue() (isZeroValue bool)
- func (a *LinkAddr) NonZero() (s string)
- func (a *LinkAddr) OneString() (s string)
- func (a *LinkAddr) SetHw(hw net.HardwareAddr) (err error)
- func (a *LinkAddr) SetName(name string)
- func (a *LinkAddr) String() (s string)
- func (a *LinkAddr) UpdateFrom(b *LinkAddr) (isComplete bool)
- func (a *LinkAddr) UpdateName() (linkAddr *LinkAddr, err error)
- func (a *LinkAddr) ZoneID() string
- type Message
- type NameCacher
- type Network
- type NextHop
- func NewNextHop(gateway netip.Addr, linkAddr *LinkAddr, src netip.Addr) (nextHop *NextHop)
- func NewNextHop2(index IfIndex, gateway netip.Addr, src netip.Addr) (next *NextHop, err error)
- func NewNextHop3(gateway netip.Addr, linkAddr *LinkAddr, src netip.Addr, nIPv4, nIPv6 int) (nextHop *NextHop)
- func NewNextHopCounts(gateway netip.Addr, linkAddr *LinkAddr, src netip.Addr, ...) (nextHop *NextHop, err error)
- func (n *NextHop) Dump() (s string)
- func (n *NextHop) HasGateway() bool
- func (n *NextHop) HasSrc() bool
- func (n *NextHop) IsZeroValue() (isZeroValue bool)
- func (n *NextHop) Name(useNameCache ...NameCacher) (name string, err error)
- func (n *NextHop) String() (s string)
- func (n *NextHop) Target() (gateway netip.Addr, s string)
- type Route
- type SocketAddress
- type SocketListener
- func (s *SocketListener[C]) AcceptConnections(handler func(C)) (goodClose bool)
- func (s *SocketListener[C]) AddrPort() (addrPort netip.AddrPort, err error)
- func (s *SocketListener[C]) Close() (err error)
- func (s *SocketListener[C]) Err(errp *error)
- func (s *SocketListener[C]) Errs() (errs parl.Errs)
- func (s *SocketListener[C]) IsAccept() (isAcceptThread bool)
- func (s *SocketListener[C]) Listen(socketString string) (err error)
- func (s *SocketListener[C]) SetThreadSource(threadSource ThreadSource[C])
- func (s *SocketListener[C]) WaitCh() (closeWait chan struct{})
- type SocketTransport
- type TCPListener
- type Tcp
- type ThreadSource
- type UDP
- type UDPFunc
Constants ¶
const ( // byte length of 48-bit hardware address HardwareAddrMac48 = 6 // byte length of 64-bit hardware address HardwareAddrEui64 = 8 // byte length of 160-bit hardware address HardwareAddrInfini = 20 )
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 )
const Do46 = true
const (
UseInterfaceNameCache = true
)
Variables ¶
var DefaultRouteIPv4 = netip.MustParsePrefix("0.0.0.0/0")
DefaultRouteIPv4 is the default route “0/0” for IPv4
var DefaultRouteIPv6 = netip.MustParsePrefix("::/0")
DefaultRouteIPv6 is the default route “::/0” for IPv6
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) { …
var HardwareAddrLengths = []int{HardwareAddrMac48, HardwareAddrEui64, HardwareAddrInfini}
list of allowable length for hardware address
var HardwareAddrLengthsWithZero = append([]int{0}, HardwareAddrLengths...)
list of aallowable lengths for ardware addresss including zero
var IPv4DefaultNetwork = netip.MustParsePrefix("0.0.0.0/0")
var IPv4VpnPrefix = netip.MustParsePrefix("0.0.0.0/1")
var IPv4loopback = net.IPv4(127, 0, 0, 1)
IPv4loopback is net.IP for localhost
- similar to net.IPv6loopback 16-byte “::1”
- outdated net.IP is used with x509.Certificate
var IPv6DefaultNetwork = netip.MustParsePrefix("::/0")
var IPv6VpnPrefix = netip.MustParsePrefix("::/3")
var LocalHost = "localhost"
var VPNRoute0IPv4 = netip.MustParsePrefix("0.0.0.0/1")
VPNRoute0IPv4 is overriding VPN route “0/1” for IPv4
var VPNRoute128IPv4 = netip.MustParsePrefix("128.0.0.0/1")
VPNRoute128IPv4 is overriding VPN route “128/1” for IPv4
var VPNRouteIPv6 = netip.MustParsePrefix("::/3")
VPNRouteIPv6 is overriding VPN route “::/3” for IPv6
Functions ¶
func Addr46 ¶ added in v0.4.112
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
AddrPortFromAddr converts tcp-protocol string-based net.Addr to binary netip.AddrPort
- addr should be net.Addr for tcp-network address implemented by net.TCPAddr
- netip.AddrPort is a binary-coded socket address
- net.Addr is legacy for net.Dial using strings for Network and socket address
- net.TCPAddr returns
- — Network “tcp”
- — String like “[fe80::%eth0]:80”
func AddrPortToTCPAddr ¶ added in v0.4.87
AddrPortToTCPAddr: Network() "tcp"
func AddrPortToUDPAddr ¶ added in v0.4.87
AddrPortToUDPAddr: Network() "udp"
func AddrPortToUDPAddr2 ¶ added in v0.4.91
func AddrSlicetoPrefix ¶ added in v0.4.112
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
AddrToIPAddr returns the net.Addr for an netip.Addr
- net.Addr is legacy interface for net.Dial using strings
- — net.Addr.Network is string like “tcp”
- — net.Addr.String is socket address literal like “1.2.3.4:80”
- netip.Addr is binary value-literals based on integers
- net.IPAddr is a legacy implementation of net.Addr for IPv4 or IPv6 addresses
- — net.IPAddr.Network returns “ip”
- — net.IPAddr.String returns “1.2.3.4” or “fe80::%eth0”
func CachedName ¶ added in v0.4.88
CachedName returns a possible name for an index. Thread-Safe
- allows consumers to retrieve names of interfaces no longer up
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 HardwareAddrInterface ¶ added in v0.4.87
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
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
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 InvertMask ¶
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 ¶
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 ¶
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
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
IsHardwareAddrLength returns true if byte-slice length is allowed hardwware address length
func IsNetwork ¶
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
IsNonGlobalIPv6 returns if addr is an IPv6 address that should have zone
func Listen ¶ added in v0.4.151
func Listen( socketAddress SocketAddress, cancel ...*atomic.Pointer[context.CancelFunc], ) (listener net.Listener, err error)
Listen obtains a tcp or stream-oriented domain-socket listener
- for connection-oriented and their derived protocols like https
- socketAddress: contains:
- — Network tcp/tcp4/tcp6 and either
- — an IPv4/IPv6 netip.AddrPort literal or
- — domain name resolving to a local interface: “example.com:1234”
- — domain-socket address “/socket” “@socket”
- — for tcp, zero port number selects an ephemeral port
- — if IPv6 is supported, “localhost” typically becomes “::” not “::1”
- cancel: optional pointer that is set to a cancel function during listen invocation
- invokes net.ListenConfig.Listen
- network value is not used by the kernel, it is a standard-library scoped helper
- TODO 240616 possibly refactor cancel argument
func MaskToBits ¶ added in v0.4.86
MaskToBits returns number of leading 1-bits in byts
- convert from net.IPMask to netip.Prefix
func NetworkPrefixBitCount ¶ added in v0.4.29
func NewTLSConfig ¶
func NewTLSConfig(cert *x509.Certificate) (tlsConfig *tls.Config)
NewTLSConfig returns a TLS configuration that has cert as a root certificate
- this allows a client to access a server that has self-signed certificate
func SplitAddrPort ¶ added in v0.4.87
func UpdateNameCache ¶ added in v0.4.87
func UpdateNameCache() (err error)
UpdateNameCache updates the static cache for local network interface names
- provides names of interfaces that are no longer up
- allows consumers to force cache update after starting an interface that may be set to down later
- the map is updated on executable launch
- Thread-Safe
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
type AddrPort ¶ added in v0.4.185
type AddrPort interface { // socket address as [netip.AddrPort] // - if no IP literal exists, [netip.AddrPort.IsValid] is false AddrPort() (addrPort netip.AddrPort) // string representation of this address. May be: // - string value of [SocketAddress.AddrPort]: “1.2.3.4:5” “[::1]:2” // - a domain name “example.com:1234” // - a domain-socket address “/socket” “@socket” // - empty string if domain is empty or AddrPort is invalid fmt.Stringer }
AddrPort may hold address and port for IP, TCP, UDP, domain-socket or derived protocols
- used for listeners or outbound connections
- for TCP UDP IP networks:
- — address empty or
- — literal unspecified IP address:
- — Listen listens on all available unicast and anycast IP addresses
- port 0: listener picks an ephemeral port
- implemented by netip.AddrPort
- created by NewAddrPort
- also:
- — Address
- — SocketAddress
- — Network
func NewAddrPort ¶ added in v0.4.185
type Address ¶ added in v0.4.185
type Address interface { // address as [netip.Addr] // - if no IP literal exists, [netip.Addr.IsValid] is false Addr() (addr netip.Addr) // string representation of this address. May be: // - string value of [Address.Addr]: “1.2.3.4” “::1” // - a domain name “example.com” // - a domain-socket address “/socket” “@socket” // - empty string if domain is empty or Addr is invalid fmt.Stringer }
Address holds an address for IP, TCP, UDP, domain-socket or derived protocols
- used for creating certificates
- created by NewAddress
- also:
- — AddrPort
- — SocketAddress
- — Network
func NewAddress ¶ added in v0.4.185
func NewAddressLiteral ¶ added in v0.4.185
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 // - Handle may be invoked zero or one time // - If Handle is not invoked, Shutdown is invoked // - conn is never nil and must be closed prior to Handle return // - a Handle invocation after Shutdown must immediately // close conn and return // - a Shutdown invocation during Handle means that Handle should return // as soon as practical: the consumer is waiting for its return // - Handle must be thread-safe versus Shutdown and [ThreadSource.Receiver] Handle(conn C) // Shutdown may be invoked any time and more than once: before, after or in lieu of Handle // - once Shutdown and any pending Handle invocation have returned: // - — resources must have been released and any connection closed // - Shutdown must be thread-safe and 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 ¶
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 IfIndex ¶
type IfIndex uint32
IfIndex is a dynamic reference to a network interface on Linux systems
func NewIfIndex ¶ added in v0.4.28
NewIfIndex returns the index of a local network interface
func NewIfIndexInt ¶ added in v0.4.86
NewIfIndexInt returns the index of a local network interface
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 augmented with cache
- useNameCache missing: cache of previously up neetwork interfaces is not used
- useNameCache pnet.Update: cache used after update
- useNameCache pnet.NoUpdate: cache used without update
- netInterface.Name is interface name “eth0”
- netInterface.Addr() returns assigned IP addresses
func (IfIndex) InterfaceIndex ¶ added in v0.4.28
Interface gets net.Interface for ifIndex
- InterfaceIndex is unique for promting methods
func (IfIndex) IsValid ¶ added in v0.4.28
IsValid determines if interface index value is set, ie. > 0
func (IfIndex) Zone ¶
Zone gets net.IPAddr.Zone string for ifIndex
- if a network interface name can be obtained, that is the zone
- if network interface name could be obtained:
- — zone non-empty, isNumeric false, err nil
- if using numeric string:
- — zone non-empty, isNumeric true, err non-nil
- ifIndex invalid: zero-values
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 mapping network-interface index to name
func (*InterfaceCache) CachedName ¶ added in v0.4.87
func (i *InterfaceCache) CachedName(ifIndex ...IfIndex) (name string, err error)
CachedName retrieves a name by index after cache update
- ifIndex: optional query to return in name after cache update
- unknown index returns empty string
- Thread-Safe
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 operation that may fail. Funtional chaining. Thread-Safe
- used for initializing a static-variable cache
type LinkAddr ¶
type LinkAddr struct { // 0 is none // - a host numbers network interfaces 1… guaranteed stable until next reboot // - operating systems tries to make index stable across reboots // - 1 is typically the local network interface IfIndex // empty for none, “lo0” “eth0” “lo” Name string // []byte physical hardware address // - 6, 8 or 20 bytes // - colon, hyphen or period separators between digits // - grouped 2-digit lower-case hex. For period separator, 4-digit net.HardwareAddr }
LinkAddr contains an Ethernet mac address, its interface name and interface index
func NewLinkAddr ¶
NewLinkAddr instantiates LinkAddr
func (*LinkAddr) Dump ¶ added in v0.4.86
Dump retuns all fields of LinkAddr for troubleshooting
- “linkAddr#28"en8"_hw00:11:22:33:44:55:66”
- zero-value: “linkAddr#0""_hw”
func (*LinkAddr) Interface ¶ added in v0.4.87
Interface returns net.Interface associated with LinkAddr
- search field order is index, name, mac
- if LinkAddr is zero-value, nil is returned
func (*LinkAddr) IsComplete ¶ added in v0.4.90
IsComplete returns true if all fields of LinkAddr have been initialized
func (*LinkAddr) IsValid ¶ added in v0.4.86
IsValid returns true if at least one field of LinkAddr has been set
func (*LinkAddr) IsZeroValue ¶ added in v0.4.86
IsZeroValue returns true if LinkAddr is uninitialized zero-value
func (*LinkAddr) NonZero ¶ added in v0.4.86
“#13_en5_00:00:5e:00:53:01” “eth0”
- zero-values are skipped
- all zero-values: “zero-value”
- never empty string
func (*LinkAddr) OneString ¶
OneString picks the most meaningful value
- interface name or hardware address or #interface index or “0”
- never empty
func (*LinkAddr) SetHw ¶ added in v0.4.86
func (a *LinkAddr) SetHw(hw net.HardwareAddr) (err error)
SetHw sets hardware address, zero-length allowed
func (*LinkAddr) UpdateFrom ¶ added in v0.4.90
UpdateFrom copies any values in b that are not in a
- returns whether all fields in a are now initialized
func (*LinkAddr) UpdateName ¶
UpdateName attempts to populate interface name if not already present
type Message ¶
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
const ( // name cache should not be used in the api call NoCache NameCacher = iota // use name cache and update the cache first Update // use name cache without update. Mechanic for ongoing name cache update is required NoUpdate )
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
ParseNetwork checks if network is valid
- tcp tcp4 tcp6 udp udp4 udp6 ip ip4 ip6 unix unixgram unixpacket
type NextHop ¶
type NextHop struct { // Gateway is set if a gateway is used to route beyond local subnets // - 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 is the hosts’s network interface where to send packets LinkAddr // Src is the source ip to use for originating packets on LinkAddr Src netip.Addr // contains filtered or unexported fields }
NextHop describes a route target
- NextHop describes how a packet is to be routed from this host towards its final destination
- NextHop is typically obtained by looking up an IP address in a routing table, ie. a collection of routing prefixes like “127/8” “::1”
- NexHop is either:
- — a local address for the host itself assigned to a local network interface
- — a subnet address for a host directly reachable via a local network interface
- — a gateway address on a subnet directly reachable via a local network interface
func NewNextHop ¶
NewNextHop assembles a route destination
- gateway: optional gateway IP
- linkAddr: optional local network interface
- src: optional source IP to use on linkAddr
func NewNextHop2 ¶
NewNextHop2 assembles a route destination based on IfIndex
func NewNextHop3 ¶ added in v0.4.90
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
- gateway: optional gateway IP
- linkAddr: optional local network interface
- src: optional source IP to use on linkAddr
- useNameCache missing: name cache is not used
- useNameCache pnet.Update: name cache is used and first updated
- useNameCache pnet.NoUpdate: name cache is used without update -
- the name cache contains local network interface names for interfaces that are no longer up
- if input LinkAddr does not have interface name, interface name is added to output nextHop
- 6in4 are converted to IPv4
func (*NextHop) HasGateway ¶
HasGateway determines if next hop uses a remote gateway
func (*NextHop) IsZeroValue ¶ added in v0.4.86
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) Target ¶
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
type SocketAddress ¶ added in v0.4.185
type SocketAddress interface { // network option, only returned in this method Network() (network Network) // socket address as [netip.AddrPort] // - if no IP literal exists, [netip.AddrPort.IsValid] is false AddrPort() (addrPort netip.AddrPort) // string representation of this address. May be: // - string value of [SocketAddress.AddrPort]: “1.2.3.4:5” “[::1]:2” // - a domain name “example.com:1234” // - a domain-socket address “/socket” “@socket” // - empty string if domain is empty or AddrPort is invalid fmt.Stringer }
SocketAddress may hold address and port for TCP, UDP or derived protocols - a socket address consists of:
- — transport protocol
- — IP address or domain
- — port number
- used for listeners or outbound connections
- for TCP UDP networks:
- — address empty or
- — literal unspecified IP address:
- — Listen listens on all available unicast and anycast IP addresses
- port 0: listener picks an ephemeral port
- created by NewSocketAddressLiteral NewSocketAddress
- also:
- — Address
- — AddrPort
- — Network
func NewSocketAddress ¶ added in v0.4.185
func NewSocketAddress(network Network, domain string) (socketAddress SocketAddress)
func NewSocketAddressLiteral ¶ added in v0.4.185
func NewSocketAddressLiteral(network Network, addrPort netip.AddrPort) (socketAddress SocketAddress)
type SocketListener ¶ added in v0.4.94
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, fieldp *SocketListener[C], errp *error, ) (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
- handler: must be non-nil or a ThreadSource must be active
- goodClose true: Accept ended with net.ErrClosed
- goodClose false: Accept ended with an unknown error
- AcceptConnections:
- — accepts connections until the socket is closed by invoking Close
- — can only be invoked once and socket state must be Listening
- — errors are streamed or collected from SocketListener.Errs
- handler or ThreadSouce 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]) 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]) Errs ¶ added in v0.4.173
func (s *SocketListener[C]) Errs() (errs parl.Errs)
Ch returns a real-time error channel
- the channel never closes
- unread errors can also be collected using [TCPListener.Err]
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])
SetThreadSource is a strategy for allocating connect threads
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 // - initialized by new-function, therefore thread-safe access 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(errp *error, network ...Network) (socket *TCPListener)
NewTCPListener returns an object for receiving tcp connections
- network is address family and type: NetworkTCP NetworkTCP4 NetworkTCP6, default IPv4
- socket implementation is net.TCPListener
- [SocketListener.Ch] returns a real-time unbound error channel or
- SocketListener.Err returns any errors appended into a single error
- TCPListener.Close is idempotent panic-free awaitable thread-safe
- SocketListener.WaitCh: channel closing on Close complete
- SocketListener.Listen: starts connection listening
- SocketListener.AddrPort: returns near socket address on successful listen
- SocketListener.AcceptConnections: provides connections to handler function until Close is invoked
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 ThreadSource ¶ added in v0.4.166
type ThreadSource[C net.Conn] interface { // Receiver prepares the ThreadSource for a possible upcoming connection // - done.Done must be invoked exactly once for all connReceiver objects // - — to ensure done invocation: // - — [ConnectionReceiver.Handle] or // - — [ConnectionReceiver.Shutdown] or both may be invoked // - Receiver and connReceiver.Handle must not block // - any connection provided to [ConnectionReceiver.Handle] must be // closed by Handle even if [ConnectionReceiver.Shutdown] was already invoked Receiver(done parl.Done, errorSink parl.ErrorSink1) (connReceiver ConnectionReceiver[C], err error) }
ThreadSource allows for a thread-allocation strategy
- for example a listener receives incoming connections for processing. ThreadSource allows for those connections to be handed to a function obtained ahead of time, thus permitting for a thread-allocation strategy to be implemented
- when ThreadSource is not used, the default allocation strategy is one new thread for each connection
- when Receiver is invoked, threads can created ahead of time for future connections and a connection-queue can be implemented
- once an incoming connection occurs, connReceiver.Handle is invoked, and that function may use threads already created by the ThreadSource held waiting at a lock
- the ThreadSource does not have shutdown. Once the listeners have concluded the ThreadSource can be shut down
- ConnectionReceiver has Shutdown and a strict protocol to prevent resource leaks
type UDP ¶
type UDP struct { Network string F UDPFunc MaxSize int net.UDPAddr // struct IP Port Zone ListenInvoked atomic.Bool StartingListen sync.WaitGroup ErrCh parl.ErrSlice IsListening atomic.Bool NetUDPConn *net.UDPConn Addr net.Addr IsShutdown atomic.Bool // contains filtered or unexported fields }
func (*UDP) Listen ¶
func (udp *UDP) Listen() (errCh parl.ErrorSource)
Source Files
¶
- action.go
- addr-port-from-addr.go
- addr-port.go
- addr.go
- address.go
- connection-receiver.go
- destination.go
- hardware-addr.go
- ifindex.go
- interface-cache.go
- interface-cacher.go
- interface.go
- linkaddr.go
- listen.go
- message.go
- name-cacher.go
- net-legacy.go
- network.go
- nexthop.go
- pnet.go
- prefix.go
- route.go
- socket-address.go
- socket-listener.go
- socket-transport.go
- tcp-listener.go
- tcp-state.go
- tcp.go
- thread-source.go
- tls-config.go
- udp.go
- vpn.go