pnet

package
v0.4.88 Latest Latest
Warning

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

Go to latest
Published: May 11, 2023 License: ISC Imports: 21 Imported by: 0

Documentation

Overview

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

Index

Constants

View Source
const (
	NoCache nameCacher = iota
	Update
	NoUpdate
)
View Source
const (
	HardwareAddrMac48  = 6
	HardwareAddrEui64  = 8
	HardwareAddrInfini = 20
)
View Source
const (
	// DefaultRouteIPv4 is the default route 0/0 for IPv4
	DefaultRouteIPv4 = "0.0.0.0/0"
	// VPNRoute0IPv4 is overriding VPN route 0/1 for IPv4
	VPNRoute0IPv4 = "0.0.0.0/1"
	// VPNRoute128IPv4 is overriding VPN route 128/1 for IPv4
	VPNRoute128IPv4 = "128.0.0.0/1"
	// DefaultRouteIPv6 is the default route ::/0 for IPv6
	DefaultRouteIPv6 = "::/0"
	// VPNRouteIPv6 is overriding VPN route ::/3 for IPv6
	VPNRouteIPv6 = "::/3"
)
View Source
const (
	TCPNetwork = "tcp"
)
View Source
const (
	UseInterfaceNameCache = true
)

Variables

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")

Functions

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 AddrToIPAddr added in v0.4.87

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

AddrToIPAddr: Network() "ip", no port number

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 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 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, isNumeric false
  • numeric zone "1": hasZone true, isNumeric false
  • interface-name zone "eth0": hasZone, isNumeric true

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) 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 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 HandlerFunc

type HandlerFunc func(http.ResponseWriter, *http.Request)

type Http

type Http struct {
	Network string // "tcp", "tcp4", "tcp6", "unix" or "unixpacket"
	http.Server
	ListenInvoked parl.AtomicBool
	ReadyWg       sync.WaitGroup
	ErrCh         chan<- error
	ErrChMutex    sync.Mutex
	ErrChClosed   parl.AtomicBool
	net.Addr      // interface
	IsListening   parl.AtomicBool
	IsShutdown    parl.AtomicBool
}

func NewHttp

func NewHttp(host, network string) (hp *Http)

NewHttp creates http server host is host:port, default ":http"

func (*Http) CloseErr

func (hp *Http) CloseErr()

func (*Http) HandleFunc

func (hp *Http) HandleFunc(pattern string, handler HandlerFunc)

func (*Http) Listen

func (hp *Http) Listen() (errCh <-chan error)

func (*Http) Listener

func (hp *Http) Listener() (listener net.Listener, err error)

func (*Http) SendErr

func (hp *Http) SendErr(err error)

func (*Http) Shutdown

func (hp *Http) Shutdown()

func (*Http) SubListen

func (hp *Http) SubListen() (errCh <-chan error)

func (*Http) WaitForUp

func (hp *Http) WaitForUp() (isUp bool, addr net.Addr)

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 Https

type Https struct {
	Http
	Cert    parl.CertificateDer
	Private crypto.Signer
}

func NewHttps

func NewHttps(host, network string, certDER parl.CertificateDer, signer crypto.Signer) (hp *Https)

func (*Https) Listen

func (hp *Https) Listen() (errCh <-chan error)

func (*Https) TLS

func (hp *Https) TLS() (tlsListener net.Listener, 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
}

func NewInterfaceCache added in v0.4.87

func NewInterfaceCache() (interfaceCache *InterfaceCache)

func (*InterfaceCache) CachedName added in v0.4.87

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

func (*InterfaceCache) CachedNameNoUpdate added in v0.4.87

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

func (*InterfaceCache) Init added in v0.4.87

func (i *InterfaceCache) Init() (i2 *InterfaceCache)

func (*InterfaceCache) Map added in v0.4.87

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

func (*InterfaceCache) Update added in v0.4.87

func (i *InterfaceCache) Update() (err error)

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) 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) String

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

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

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)
	fmt.Stringer
}

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

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 EmptyNextHop

func EmptyNextHop() *NextHop

EmptyNextHop provides empty NextHop

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 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 (nh *NextHop) HasGateway() bool

HasGateway determines if next hop uses a remote gateway

func (*NextHop) HasSrc

func (nh *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 (nextHop *NextHop) String() (s string)

func (*NextHop) Target

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

Target describes the detination for this next hop

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 TCPListener added in v0.4.62

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

TCPListener embeds net.TCPListener

  • NewListenTCP4 initializes
  • go AcceptThread handles inbound connections
  • Ch provides the error channel
  • Close closes TCPListener
  • Wait awaits last handler exit

func NewListenTCP4 added in v0.4.62

func NewListenTCP4(socketString string, handler func(net.Conn)) (socket *TCPListener, err error)

NewListenTCP4 returns a tcp listener on a local IPv4 network interface

  • socketString is host:port "1.2.3.4:80"
  • — host must be literal IPv4 address 1.2.3.4
  • — port must be literal port number 0…65534 where 0 means a temporary port
  • network is always "tcp4"
  • handler must invoke net.Conn.Close

func (*TCPListener) AcceptThread added in v0.4.62

func (s *TCPListener) AcceptThread()

AcceptThread is a goroutine handling inbound connections

func (*TCPListener) Ch added in v0.4.62

func (s *TCPListener) Ch() (ch <-chan error)

func (*TCPListener) Err added in v0.4.62

func (s *TCPListener) Err(errp *error)

func (*TCPListener) IsAcceptThread added in v0.4.62

func (s *TCPListener) IsAcceptThread() (isAcceptThread bool)

IsAcceptThread indicates whether the listener is functional and accepting incoming connections

func (*TCPListener) Wait added in v0.4.62

func (s *TCPListener) Wait()

Wait waits for all connections and the handler thread to exit. ListenTCP4.Close needs to be invoked

type Tcp

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

type UDP

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

	Addr       net.Addr
	IsShutdown parl.AtomicBool
	// 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