sockaddr

package module
v1.0.6 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2023 License: MPL-2.0 Imports: 12 Imported by: 381

README

go-sockaddr

sockaddr Library

Socket address convenience functions for Go. go-sockaddr is a convenience library that makes doing the right thing with IP addresses easy. go-sockaddr is loosely modeled after the UNIX sockaddr_t and creates a union of the family of sockaddr_t types (see below for an ascii diagram). Library documentation is available at https://godoc.org/github.com/hashicorp/go-sockaddr. The primary intent of the library was to make it possible to define heuristics for selecting the correct IP addresses when a configuration is evaluated at runtime. See the docs, template package, tests, and CLI utility for details and hints as to how to use this library.

For example, with this library it is possible to find an IP address that:

Or any combination or variation therein.

There are also a few simple helper functions such as GetPublicIP and GetPrivateIP which both return strings and select the first public or private IP address on the default interface, respectively. Similarly, there is also a helper function called GetInterfaceIP which returns the first usable IP address on the named interface.

sockaddr CLI

Given the possible complexity of the sockaddr library, there is a CLI utility that accompanies the library, also called sockaddr. The sockaddr utility exposes nearly all of the functionality of the library and can be used either as an administrative tool or testing tool. To install the sockaddr, run:

$ go get -u github.com/hashicorp/go-sockaddr/cmd/sockaddr

If you're familiar with UNIX's sockaddr struct's, the following diagram mapping the C sockaddr (top) to go-sockaddr structs (bottom) and interfaces will be helpful:

+-------------------------------------------------------+
|                                                       |
|                        sockaddr                       |
|                        SockAddr                       |
|                                                       |
| +--------------+ +----------------------------------+ |
| | sockaddr_un  | |                                  | |
| | SockAddrUnix | |           sockaddr_in{,6}        | |
| +--------------+ |                IPAddr            | |
|                  |                                  | |
|                  | +-------------+ +--------------+ | |
|                  | | sockaddr_in | | sockaddr_in6 | | |
|                  | |   IPv4Addr  | |   IPv6Addr   | | |
|                  | +-------------+ +--------------+ | |
|                  |                                  | |
|                  +----------------------------------+ |
|                                                       |
+-------------------------------------------------------+

Inspiration and Design

There were many subtle inspirations that led to this design, but the most direct inspiration for the filtering syntax was OpenBSD's pf.conf(5) firewall syntax that lets you select the first IP address on a given named interface. The original problem stemmed from:

  • needing to create immutable images using Packer that ran the Consul process (Consul can only use one IP address at a time);
  • images that may or may not have multiple interfaces or IP addresses at runtime; and
  • we didn't want to rely on configuration management to render out the correct IP address if the VM image was being used in an auto-scaling group.

Instead we needed some way to codify a heuristic that would correctly select the right IP address but the input parameters were not known when the image was created.

Documentation

Overview

Package sockaddr is a Go implementation of the UNIX socket family data types and related helper functions.

Index

Constants

View Source
const (
	IPv3len = 6
	IPv4len = 4
	IPv6len = 16
)

Constants for the sizes of IPv3, IPv4, and IPv6 address types.

View Source
const (
	TypeUnknown SockAddrType = 0x0
	TypeUnix                 = 0x1
	TypeIPv4                 = 0x2
	TypeIPv6                 = 0x4

	// TypeIP is the union of TypeIPv4 and TypeIPv6
	TypeIP = 0x6
)
View Source
const ForwardingBlacklist = 4294967295

ForwardingBlacklist is a faux RFC that includes a list of non-forwardable IP blocks.

View Source
const ForwardingBlacklistRFC = "4294967295"
View Source
const IPv4HostMask = IPv4Mask(0xffffffff)

IPv4HostMask is a constant represents a /32 IPv4 Address (i.e. 255.255.255.255).

View Source
const IPv6HostPrefix = IPPrefixLen(128)

IPv6HostPrefix is a constant represents a /128 IPv6 Prefix.

Variables

View Source
var (
	ErrNoInterface = errors.New("No default interface found (unsupported platform)")
	ErrNoRoute     = errors.New("no route info found (unsupported platform)")
)

Functions

func AscAddress

func AscAddress(p1Ptr, p2Ptr *SockAddr) int

AscAddress is a sorting function to sort SockAddrs by their respective address type. Non-equal types are deferred in the sort.

func AscIfAddress

func AscIfAddress(p1Ptr, p2Ptr *IfAddr) int

AscIfAddress is a sorting function to sort IfAddrs by their respective address type. Non-equal types are deferred in the sort.

func AscIfDefault

func AscIfDefault(p1Ptr, p2Ptr *IfAddr) int

AscIfDefault is a sorting function to sort IfAddrs by whether or not they have a default route or not. Non-equal types are deferred in the sort.

FIXME: This is a particularly expensive sorting operation because of the non-memoized calls to NewRouteInfo(). In an ideal world the routeInfo data once at the start of the sort and pass it along as a context or by wrapping the IfAddr type with this information (this would also solve the inability to return errors and the possibility of failing silently). Fortunately, N*log(N) where N = 3 is only ~6.2 invocations. Not ideal, but not worth optimizing today. The common case is this gets called once or twice. Patches welcome.

func AscIfName

func AscIfName(p1Ptr, p2Ptr *IfAddr) int

AscIfName is a sorting function to sort IfAddrs by their interface names.

func AscIfNetworkSize

func AscIfNetworkSize(p1Ptr, p2Ptr *IfAddr) int

AscIfNetworkSize is a sorting function to sort IfAddrs by their respective network mask size.

func AscIfPort

func AscIfPort(p1Ptr, p2Ptr *IfAddr) int

AscIfPort is a sorting function to sort IfAddrs by their respective port type. Non-equal types are deferred in the sort.

func AscIfPrivate

func AscIfPrivate(p1Ptr, p2Ptr *IfAddr) int

AscIfPrivate is a sorting function to sort IfAddrs by "private" values before "public" values. Both IPv4 and IPv6 are compared against RFC6890 (RFC6890 includes, and is not limited to, RFC1918 and RFC6598 for IPv4, and IPv6 includes RFC4193).

func AscIfType

func AscIfType(p1Ptr, p2Ptr *IfAddr) int

AscIfType is a sorting function to sort IfAddrs by their respective address type. Non-equal types are deferred in the sort.

func AscNetworkSize

func AscNetworkSize(p1Ptr, p2Ptr *SockAddr) int

AscNetworkSize is a sorting function to sort SockAddrs based on their network size. Non-equal types are deferred in the sort.

func AscPort

func AscPort(p1Ptr, p2Ptr *SockAddr) int

AscPort is a sorting function to sort SockAddrs by their respective address type. Non-equal types are deferred in the sort.

func AscPrivate

func AscPrivate(p1Ptr, p2Ptr *SockAddr) int

AscPrivate is a sorting function to sort "more secure" private values before "more public" values. Both IPv4 and IPv6 are compared against RFC6890 (RFC6890 includes, and is not limited to, RFC1918 and RFC6598 for IPv4, and IPv6 includes RFC4193).

func AscType

func AscType(p1Ptr, p2Ptr *SockAddr) int

AscType is a sorting function to sort "more secure" types before "less-secure" types.

func Attr

func Attr(sa SockAddr, attrName AttrName) (string, error)

Attr returns the named attribute as a string

func DescIfAddress

func DescIfAddress(p1Ptr, p2Ptr *IfAddr) int

DescIfAddress is identical to AscIfAddress but reverse ordered.

func DescIfDefault

func DescIfDefault(p1Ptr, p2Ptr *IfAddr) int

DescIfDefault is identical to AscIfDefault but reverse ordered.

func DescIfName

func DescIfName(p1Ptr, p2Ptr *IfAddr) int

DescIfName is identical to AscIfName but reverse ordered.

func DescIfNetworkSize

func DescIfNetworkSize(p1Ptr, p2Ptr *IfAddr) int

DescIfNetworkSize is identical to AscIfNetworkSize but reverse ordered.

func DescIfPort

func DescIfPort(p1Ptr, p2Ptr *IfAddr) int

DescIfPort is identical to AscIfPort but reverse ordered.

func DescIfPrivate

func DescIfPrivate(p1Ptr, p2Ptr *IfAddr) int

DescIfPrivate is identical to AscIfPrivate but reverse ordered.

func DescIfType

func DescIfType(p1Ptr, p2Ptr *IfAddr) int

DescIfType is identical to AscIfType but reverse ordered.

func GetInterfaceIP

func GetInterfaceIP(namedIfRE string) (string, error)

GetInterfaceIP returns a string with a single IP address sorted by the size of the network (i.e. IP addresses with a smaller netmask, larger network size, are sorted first). This function is the `eval` equivalent of:

``` $ sockaddr eval -r '{{GetAllInterfaces | include "name" <<ARG>> | sort "type,size" | include "flag" "forwardable" | attr "address" }}' / ```

func GetInterfaceIPs

func GetInterfaceIPs(namedIfRE string) (string, error)

GetInterfaceIPs returns a string with all IPs, sorted by the size of the network (i.e. IP addresses with a smaller netmask, larger network size, are sorted first), on a named interface. This function is the `eval` equivalent of:

``` $ sockaddr eval -r '{{GetAllInterfaces | include "name" <<ARG>> | sort "type,size" | join "address" " "}}' / ```

func GetPrivateIP

func GetPrivateIP() (string, error)

GetPrivateIP returns a string with a single IP address that is part of RFC 6890 and has a default route. If the system can't determine its IP address or find an RFC 6890 IP address, an empty string will be returned instead. This function is the `eval` equivalent of:

``` $ sockaddr eval -r '{{GetPrivateInterfaces | attr "address"}}' / ```

func GetPrivateIPs

func GetPrivateIPs() (string, error)

GetPrivateIPs returns a string with all IP addresses that are part of RFC 6890 (regardless of whether or not there is a default route, unlike GetPublicIP). If the system can't find any RFC 6890 IP addresses, an empty string will be returned instead. This function is the `eval` equivalent of:

``` $ sockaddr eval -r '{{GetAllInterfaces | include "RFC" "6890" | join "address" " "}}' / ```

func GetPublicIP

func GetPublicIP() (string, error)

GetPublicIP returns a string with a single IP address that is NOT part of RFC 6890 and has a default route. If the system can't determine its IP address or find a non RFC 6890 IP address, an empty string will be returned instead. This function is the `eval` equivalent of:

``` $ sockaddr eval -r '{{GetPublicInterfaces | attr "address"}}' / ```

func GetPublicIPs

func GetPublicIPs() (string, error)

GetPublicIPs returns a string with all IP addresses that are NOT part of RFC 6890 (regardless of whether or not there is a default route, unlike GetPublicIP). If the system can't find any non RFC 6890 IP addresses, an empty string will be returned instead. This function is the `eval` equivalent of:

``` $ sockaddr eval -r '{{GetAllInterfaces | exclude "RFC" "6890" | join "address" " "}}' / ```

func IPAddrAttr

func IPAddrAttr(ip IPAddr, selector AttrName) string

IPAddrAttr returns a string representation of an attribute for the given IPAddr.

func IPv4AddrAttr

func IPv4AddrAttr(ipv4 IPv4Addr, selector AttrName) string

IPv4AddrAttr returns a string representation of an attribute for the given IPv4Addr.

func IPv6AddrAttr

func IPv6AddrAttr(ipv6 IPv6Addr, selector AttrName) string

IPv6AddrAttr returns a string representation of an attribute for the given IPv6Addr.

func IfAddrAttr

func IfAddrAttr(ifAddr IfAddr, attrName AttrName) string

IfAddrAttr returns a string representation of an attribute for the given IfAddr.

func IfAttr

func IfAttr(selectorName string, ifAddr IfAddr) (string, error)

IfAttr forwards the selector to IfAttr.Attr() for resolution. If there is more than one IfAddr, only the first IfAddr is used.

func IfAttrs

func IfAttrs(selectorName string, ifAddrs IfAddrs) (string, error)

IfAttrs forwards the selector to IfAttrs.Attr() for resolution. If there is more than one IfAddr, only the first IfAddr is used.

func IfByNetwork

func IfByNetwork(selectorParam string, inputIfAddrs IfAddrs) (IfAddrs, IfAddrs, error)

IfByNetwork returns an IfAddrs that are equal to or included within the network passed in by selector.

func IsRFC

func IsRFC(rfcNum uint, sa SockAddr) bool

IsRFC tests to see if an SockAddr matches the specified RFC

func JoinIfAddrs

func JoinIfAddrs(selectorName string, joinStr string, inputIfAddrs IfAddrs) (string, error)

JoinIfAddrs joins an IfAddrs and returns a string

func KnownRFCs

func KnownRFCs() map[uint]SockAddrs

KnownRFCs returns an initial set of known RFCs.

NOTE (sean@): As this list evolves over time, please submit patches to keep this list current. If something isn't right, inquire, as it may just be a bug on my part. Some of the inclusions were based on my judgement as to what would be a useful value (e.g. RFC3330).

Useful resources:

* https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml * https://www.iana.org/assignments/ipv6-unicast-address-assignments/ipv6-unicast-address-assignments.xhtml * https://www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml

func NewRouteInfo

func NewRouteInfo() (routeInfo, error)

NewRouteInfo returns a Linux-specific implementation of the RouteInfo interface.

func OrderedAddrBy

func OrderedAddrBy(cmpFuncs ...CmpAddrFunc) *multiAddrSorter

OrderedAddrBy sorts SockAddr by the list of sort function pointers.

func OrderedIfAddrBy

func OrderedIfAddrBy(cmpFuncs ...CmpIfAddrFunc) *multiIfAddrSorter

OrderedIfAddrBy sorts SockAddr by the list of sort function pointers.

func SockAddrAttr

func SockAddrAttr(sa SockAddr, selector AttrName) string

SockAddrAttr returns a string representation of an attribute for the given SockAddr.

func UnixSockAttr

func UnixSockAttr(us UnixSock, attrName AttrName) string

UnixSockAttr returns a string representation of an attribute for the given UnixSock.

func VisitAllRFCs

func VisitAllRFCs(fn func(rfcNum uint, sockaddrs SockAddrs))

VisitAllRFCs iterates over all known RFCs and calls the visitor

Types

type AttrName

type AttrName string

func IPAttrs

func IPAttrs() []AttrName

IPAttrs returns a list of attributes supported by the IPAddr type

func IPv4Attrs

func IPv4Attrs() []AttrName

IPv4Attrs returns a list of attributes supported by the IPv4Addr type

func IPv6Attrs

func IPv6Attrs() []AttrName

IPv6Attrs returns a list of attributes supported by the IPv6Addr type

func IfAddrAttrs

func IfAddrAttrs() []AttrName

IfAddrAttrs returns a list of attributes supported by the IfAddr type

func SockAddrAttrs

func SockAddrAttrs() []AttrName

UnixSockAttrs returns a list of attributes supported by the UnixSock type

func UnixSockAttrs

func UnixSockAttrs() []AttrName

UnixSockAttrs returns a list of attributes supported by the UnixSockAddr type

type CmpAddrFunc

type CmpAddrFunc func(p1, p2 *SockAddr) int

CmpAddrFunc is the function signature that must be met to be used in the OrderedAddrBy multiAddrSorter

type CmpIfAddrFunc

type CmpIfAddrFunc func(p1, p2 *IfAddr) int

CmpIfFunc is the function signature that must be met to be used in the OrderedIfAddrBy multiIfAddrSorter

type IPAddr

type IPAddr interface {
	SockAddr
	AddressBinString() string
	AddressHexString() string
	Cmp(SockAddr) int
	CmpAddress(SockAddr) int
	CmpPort(SockAddr) int
	FirstUsable() IPAddr
	Host() IPAddr
	IPPort() IPPort
	LastUsable() IPAddr
	Maskbits() int
	NetIP() *net.IP
	NetIPMask() *net.IPMask
	NetIPNet() *net.IPNet
	Network() IPAddr
	Octets() []int
}

IPAddr is a generic IP address interface for IPv4 and IPv6 addresses, networks, and socket endpoints.

func MustIPAddr

func MustIPAddr(addr string) IPAddr

MustIPAddr is a helper method that must return an IPAddr or panic on invalid input.

func NewIPAddr

func NewIPAddr(addr string) (IPAddr, error)

NewIPAddr creates a new IPAddr from a string. Returns nil if the string is not an IPv4 or an IPv6 address.

func ToIPAddr

func ToIPAddr(sa SockAddr) *IPAddr

ToIPAddr returns an IPAddr type or nil if the type conversion fails.

type IPAddrs

type IPAddrs []IPAddr

func (IPAddrs) Len

func (s IPAddrs) Len() int

func (IPAddrs) Swap

func (s IPAddrs) Swap(i, j int)

type IPPort

type IPPort uint16

IPPort is the type for an IP port number for the TCP and UDP IP transports.

type IPPrefixLen

type IPPrefixLen byte

IPPrefixLen is a typed integer representing the prefix length for a given IPAddr.

type IPv4Addr

type IPv4Addr struct {
	IPAddr
	Address IPv4Address
	Mask    IPv4Mask
	Port    IPPort
}

IPv4Addr implements a convenience wrapper around the union of Go's built-in net.IP and net.IPNet types. In UNIX-speak, IPv4Addr implements `sockaddr` when the the address family is set to AF_INET (i.e. `sockaddr_in`).

func MustIPv4Addr

func MustIPv4Addr(addr string) IPv4Addr

MustIPv4Addr is a helper method that must return an IPv4Addr or panic on invalid input.

func NewIPv4Addr

func NewIPv4Addr(ipv4Str string) (IPv4Addr, error)

NewIPv4Addr creates an IPv4Addr from a string. String can be in the form of either an IPv4:port (e.g. `1.2.3.4:80`, in which case the mask is assumed to be a `/32`), an IPv4 address (e.g. `1.2.3.4`, also with a `/32` mask), or an IPv4 CIDR (e.g. `1.2.3.4/24`, which has its IP port initialized to zero). ipv4Str can not be a hostname.

NOTE: Many net.*() routines will initialize and return an IPv6 address. To create uint32 values from net.IP, always test to make sure the address returned can be converted to a 4 byte array using To4().

func ToIPv4Addr

func ToIPv4Addr(sa SockAddr) *IPv4Addr

ToIPv4Addr returns an IPv4Addr type or nil if the type conversion fails.

func (IPv4Addr) AddressBinString

func (ipv4 IPv4Addr) AddressBinString() string

AddressBinString returns a string with the IPv4Addr's Address represented as a sequence of '0' and '1' characters. This method is useful for debugging or by operators who want to inspect an address.

func (IPv4Addr) AddressHexString

func (ipv4 IPv4Addr) AddressHexString() string

AddressHexString returns a string with the IPv4Addr address represented as a sequence of hex characters. This method is useful for debugging or by operators who want to inspect an address.

func (IPv4Addr) Broadcast

func (ipv4 IPv4Addr) Broadcast() IPAddr

Broadcast is an IPv4Addr-only method that returns the broadcast address of the network.

NOTE: IPv6 only supports multicast, so this method only exists for IPv4Addr.

func (IPv4Addr) BroadcastAddress

func (ipv4 IPv4Addr) BroadcastAddress() IPv4Network

BroadcastAddress returns a IPv4Network of the IPv4Addr's broadcast address.

func (IPv4Addr) CmpAddress

func (ipv4 IPv4Addr) CmpAddress(sa SockAddr) int

CmpAddress follows the Cmp() standard protocol and returns:

  • -1 If the receiver should sort first because its address is lower than arg
  • 0 if the SockAddr arg is equal to the receiving IPv4Addr or the argument is of a different type.
  • 1 If the argument should sort first.

func (IPv4Addr) CmpPort

func (ipv4 IPv4Addr) CmpPort(sa SockAddr) int

CmpPort follows the Cmp() standard protocol and returns:

  • -1 If the receiver should sort first because its port is lower than arg
  • 0 if the SockAddr arg's port number is equal to the receiving IPv4Addr, regardless of type.
  • 1 If the argument should sort first.

func (IPv4Addr) CmpRFC

func (ipv4 IPv4Addr) CmpRFC(rfcNum uint, sa SockAddr) int

CmpRFC follows the Cmp() standard protocol and returns:

  • -1 If the receiver should sort first because it belongs to the RFC and its arg does not
  • 0 if the receiver and arg both belong to the same RFC or neither do.
  • 1 If the arg belongs to the RFC but receiver does not.

func (IPv4Addr) Contains

func (ipv4 IPv4Addr) Contains(sa SockAddr) bool

Contains returns true if the SockAddr is contained within the receiver.

func (IPv4Addr) ContainsAddress

func (ipv4 IPv4Addr) ContainsAddress(x IPv4Address) bool

ContainsAddress returns true if the IPv4Address is contained within the receiver.

func (IPv4Addr) ContainsNetwork

func (ipv4 IPv4Addr) ContainsNetwork(x IPv4Addr) bool

ContainsNetwork returns true if the network from IPv4Addr is contained within the receiver.

func (IPv4Addr) DialPacketArgs

func (ipv4 IPv4Addr) DialPacketArgs() (network, dialArgs string)

DialPacketArgs returns the arguments required to be passed to net.DialUDP(). If the Mask of ipv4 is not a /32 or the Port is 0, DialPacketArgs() will fail. See Host() to create an IPv4Addr with its mask set to /32.

func (IPv4Addr) DialStreamArgs

func (ipv4 IPv4Addr) DialStreamArgs() (network, dialArgs string)

DialStreamArgs returns the arguments required to be passed to net.DialTCP(). If the Mask of ipv4 is not a /32 or the Port is 0, DialStreamArgs() will fail. See Host() to create an IPv4Addr with its mask set to /32.

func (IPv4Addr) Equal

func (ipv4 IPv4Addr) Equal(sa SockAddr) bool

Equal returns true if a SockAddr is equal to the receiving IPv4Addr.

func (IPv4Addr) FirstUsable

func (ipv4 IPv4Addr) FirstUsable() IPAddr

FirstUsable returns an IPv4Addr set to the first address following the network prefix. The first usable address in a network is normally the gateway and should not be used except by devices forwarding packets between two administratively distinct networks (i.e. a router). This function does not discriminate against first usable vs "first address that should be used." For example, FirstUsable() on "192.168.1.10/24" would return the address "192.168.1.1/24".

func (IPv4Addr) Host

func (ipv4 IPv4Addr) Host() IPAddr

Host returns a copy of ipv4 with its mask set to /32 so that it can be used by DialPacketArgs(), DialStreamArgs(), ListenPacketArgs(), or ListenStreamArgs().

func (IPv4Addr) IPPort

func (ipv4 IPv4Addr) IPPort() IPPort

IPPort returns the Port number attached to the IPv4Addr

func (IPv4Addr) LastUsable

func (ipv4 IPv4Addr) LastUsable() IPAddr

LastUsable returns the last address before the broadcast address in a given network.

func (IPv4Addr) ListenPacketArgs

func (ipv4 IPv4Addr) ListenPacketArgs() (network, listenArgs string)

ListenPacketArgs returns the arguments required to be passed to net.ListenUDP(). If the Mask of ipv4 is not a /32, ListenPacketArgs() will fail. See Host() to create an IPv4Addr with its mask set to /32.

func (IPv4Addr) ListenStreamArgs

func (ipv4 IPv4Addr) ListenStreamArgs() (network, listenArgs string)

ListenStreamArgs returns the arguments required to be passed to net.ListenTCP(). If the Mask of ipv4 is not a /32, ListenStreamArgs() will fail. See Host() to create an IPv4Addr with its mask set to /32.

func (IPv4Addr) Maskbits

func (ipv4 IPv4Addr) Maskbits() int

Maskbits returns the number of network mask bits in a given IPv4Addr. For example, the Maskbits() of "192.168.1.1/24" would return 24.

func (IPv4Addr) NetIP

func (ipv4 IPv4Addr) NetIP() *net.IP

NetIP returns the address as a net.IP (address is always presized to IPv4).

func (IPv4Addr) NetIPMask

func (ipv4 IPv4Addr) NetIPMask() *net.IPMask

NetIPMask create a new net.IPMask from the IPv4Addr.

func (IPv4Addr) NetIPNet

func (ipv4 IPv4Addr) NetIPNet() *net.IPNet

NetIPNet create a new net.IPNet from the IPv4Addr.

func (IPv4Addr) Network

func (ipv4 IPv4Addr) Network() IPAddr

Network returns the network prefix or network address for a given network.

func (IPv4Addr) NetworkAddress

func (ipv4 IPv4Addr) NetworkAddress() IPv4Network

NetworkAddress returns an IPv4Network of the IPv4Addr's network address.

func (IPv4Addr) Octets

func (ipv4 IPv4Addr) Octets() []int

Octets returns a slice of the four octets in an IPv4Addr's Address. The order of the bytes is big endian.

func (IPv4Addr) String

func (ipv4 IPv4Addr) String() string

String returns a string representation of the IPv4Addr

func (IPv4Addr) Type

func (IPv4Addr) Type() SockAddrType

Type is used as a type switch and returns TypeIPv4

type IPv4Address

type IPv4Address uint32

IPv4Address is a named type representing an IPv4 address.

type IPv4Mask

type IPv4Mask uint32

IPv4Mask is a named type representing an IPv4 network mask.

type IPv4Network

type IPv4Network uint32

IPv4Network is a named type representing an IPv4 network.

type IPv6Addr

type IPv6Addr struct {
	IPAddr
	Address IPv6Address
	Mask    IPv6Mask
	Port    IPPort
}

IPv6Addr implements a convenience wrapper around the union of Go's built-in net.IP and net.IPNet types. In UNIX-speak, IPv6Addr implements `sockaddr` when the the address family is set to AF_INET6 (i.e. `sockaddr_in6`).

func MustIPv6Addr

func MustIPv6Addr(addr string) IPv6Addr

MustIPv6Addr is a helper method that must return an IPv6Addr or panic on invalid input.

func NewIPv6Addr

func NewIPv6Addr(ipv6Str string) (IPv6Addr, error)

NewIPv6Addr creates an IPv6Addr from a string. String can be in the form of an an IPv6:port (e.g. `[2001:4860:0:2001::68]:80`, in which case the mask is assumed to be a /128), an IPv6 address (e.g. `2001:4860:0:2001::68`, also with a `/128` mask), an IPv6 CIDR (e.g. `2001:4860:0:2001::68/64`, which has its IP port initialized to zero). ipv6Str can not be a hostname.

NOTE: Many net.*() routines will initialize and return an IPv4 address. Always test to make sure the address returned cannot be converted to a 4 byte array using To4().

func ToIPv6Addr

func ToIPv6Addr(sa SockAddr) *IPv6Addr

ToIPv6Addr returns an IPv6Addr type or nil if the type conversion fails.

func (IPv6Addr) AddressBinString

func (ipv6 IPv6Addr) AddressBinString() string

AddressBinString returns a string with the IPv6Addr's Address represented as a sequence of '0' and '1' characters. This method is useful for debugging or by operators who want to inspect an address.

func (IPv6Addr) AddressHexString

func (ipv6 IPv6Addr) AddressHexString() string

AddressHexString returns a string with the IPv6Addr address represented as a sequence of hex characters. This method is useful for debugging or by operators who want to inspect an address.

func (IPv6Addr) CmpAddress

func (ipv6 IPv6Addr) CmpAddress(sa SockAddr) int

CmpAddress follows the Cmp() standard protocol and returns:

  • -1 If the receiver should sort first because its address is lower than arg
  • 0 if the SockAddr arg equal to the receiving IPv6Addr or the argument is of a different type.
  • 1 If the argument should sort first.

func (IPv6Addr) CmpPort

func (ipv6 IPv6Addr) CmpPort(sa SockAddr) int

CmpPort follows the Cmp() standard protocol and returns:

  • -1 If the receiver should sort first because its port is lower than arg
  • 0 if the SockAddr arg's port number is equal to the receiving IPv6Addr, regardless of type.
  • 1 If the argument should sort first.

func (IPv6Addr) CmpRFC

func (ipv6 IPv6Addr) CmpRFC(rfcNum uint, sa SockAddr) int

CmpRFC follows the Cmp() standard protocol and returns:

  • -1 If the receiver should sort first because it belongs to the RFC and its arg does not
  • 0 if the receiver and arg both belong to the same RFC or neither do.
  • 1 If the arg belongs to the RFC but receiver does not.

func (IPv6Addr) Contains

func (ipv6 IPv6Addr) Contains(sa SockAddr) bool

Contains returns true if the SockAddr is contained within the receiver.

func (IPv6Addr) ContainsAddress

func (ipv6 IPv6Addr) ContainsAddress(x IPv6Address) bool

ContainsAddress returns true if the IPv6Address is contained within the receiver.

func (IPv6Addr) ContainsNetwork

func (x IPv6Addr) ContainsNetwork(y IPv6Addr) bool

ContainsNetwork returns true if the network from IPv6Addr is contained within the receiver.

func (IPv6Addr) DialPacketArgs

func (ipv6 IPv6Addr) DialPacketArgs() (network, dialArgs string)

DialPacketArgs returns the arguments required to be passed to net.DialUDP(). If the Mask of ipv6 is not a /128 or the Port is 0, DialPacketArgs() will fail. See Host() to create an IPv6Addr with its mask set to /128.

func (IPv6Addr) DialStreamArgs

func (ipv6 IPv6Addr) DialStreamArgs() (network, dialArgs string)

DialStreamArgs returns the arguments required to be passed to net.DialTCP(). If the Mask of ipv6 is not a /128 or the Port is 0, DialStreamArgs() will fail. See Host() to create an IPv6Addr with its mask set to /128.

func (IPv6Addr) Equal

func (ipv6a IPv6Addr) Equal(sa SockAddr) bool

Equal returns true if a SockAddr is equal to the receiving IPv4Addr.

func (IPv6Addr) FirstUsable

func (ipv6 IPv6Addr) FirstUsable() IPAddr

FirstUsable returns an IPv6Addr set to the first address following the network prefix. The first usable address in a network is normally the gateway and should not be used except by devices forwarding packets between two administratively distinct networks (i.e. a router). This function does not discriminate against first usable vs "first address that should be used." For example, FirstUsable() on "2001:0db8::0003/64" would return "2001:0db8::00011".

func (IPv6Addr) Host

func (ipv6 IPv6Addr) Host() IPAddr

Host returns a copy of ipv6 with its mask set to /128 so that it can be used by DialPacketArgs(), DialStreamArgs(), ListenPacketArgs(), or ListenStreamArgs().

func (IPv6Addr) IPPort

func (ipv6 IPv6Addr) IPPort() IPPort

IPPort returns the Port number attached to the IPv6Addr

func (IPv6Addr) LastUsable

func (ipv6 IPv6Addr) LastUsable() IPAddr

LastUsable returns the last address in a given network.

func (IPv6Addr) ListenPacketArgs

func (ipv6 IPv6Addr) ListenPacketArgs() (network, listenArgs string)

ListenPacketArgs returns the arguments required to be passed to net.ListenUDP(). If the Mask of ipv6 is not a /128, ListenPacketArgs() will fail. See Host() to create an IPv6Addr with its mask set to /128.

func (IPv6Addr) ListenStreamArgs

func (ipv6 IPv6Addr) ListenStreamArgs() (network, listenArgs string)

ListenStreamArgs returns the arguments required to be passed to net.ListenTCP(). If the Mask of ipv6 is not a /128, ListenStreamArgs() will fail. See Host() to create an IPv6Addr with its mask set to /128.

func (IPv6Addr) Maskbits

func (ipv6 IPv6Addr) Maskbits() int

Maskbits returns the number of network mask bits in a given IPv6Addr. For example, the Maskbits() of "2001:0db8::0003/64" would return 64.

func (IPv6Addr) NetIP

func (ipv6 IPv6Addr) NetIP() *net.IP

NetIP returns the address as a net.IP.

func (IPv6Addr) NetIPMask

func (ipv6 IPv6Addr) NetIPMask() *net.IPMask

NetIPMask create a new net.IPMask from the IPv6Addr.

func (IPv6Addr) NetIPNet

func (ipv6 IPv6Addr) NetIPNet() *net.IPNet

Network returns a pointer to the net.IPNet within IPv4Addr receiver.

func (IPv6Addr) Network

func (ipv6 IPv6Addr) Network() IPAddr

Network returns the network prefix or network address for a given network.

func (IPv6Addr) NetworkAddress

func (ipv6 IPv6Addr) NetworkAddress() IPv6Network

NetworkAddress returns an IPv6Network of the IPv6Addr's network address.

func (IPv6Addr) Octets

func (ipv6 IPv6Addr) Octets() []int

Octets returns a slice of the 16 octets in an IPv6Addr's Address. The order of the bytes is big endian.

func (IPv6Addr) String

func (ipv6 IPv6Addr) String() string

String returns a string representation of the IPv6Addr

func (IPv6Addr) Type

func (IPv6Addr) Type() SockAddrType

Type is used as a type switch and returns TypeIPv6

type IPv6Address

type IPv6Address *big.Int

IPv6Address is a named type representing an IPv6 address.

type IPv6Mask

type IPv6Mask *big.Int

IPv6Mask is a named type representing an IPv6 network mask.

type IPv6Network

type IPv6Network *big.Int

IPv6Network is a named type representing an IPv6 network.

type IfAddr

type IfAddr struct {
	SockAddr
	net.Interface
}

IfAddr is a union of a SockAddr and a net.Interface.

func IfAddrMath

func IfAddrMath(operation, value string, inputIfAddr IfAddr) (IfAddr, error)

IfAddrMath will return a new IfAddr struct with a mutated value.

func (IfAddr) Attr

func (ifAddr IfAddr) Attr(attrName AttrName) (string, error)

Attr returns the named attribute as a string

func (IfAddr) String

func (ifAddr IfAddr) String() string

type IfAddrs

type IfAddrs []IfAddr

IfAddrs is a slice of IfAddr

func ExcludeIfs

func ExcludeIfs(selectorName, selectorParam string, inputIfAddrs IfAddrs) (IfAddrs, error)

ExcludeIfs returns an IfAddrs based on the passed in selector.

func FilterIfByType

func FilterIfByType(ifAddrs IfAddrs, type_ SockAddrType) (matchedIfs, excludedIfs IfAddrs)

FilterIfByType filters IfAddrs and returns a list of the matching type

func GetAllInterfaces

func GetAllInterfaces() (IfAddrs, error)

GetAllInterfaces iterates over all available network interfaces and finds all available IP addresses on each interface and converts them to sockaddr.IPAddrs, and returning the result as an array of IfAddr.

func GetDefaultInterfaces

func GetDefaultInterfaces() (IfAddrs, error)

GetDefaultInterfaces returns IfAddrs of the addresses attached to the default route.

func GetPrivateInterfaces

func GetPrivateInterfaces() (IfAddrs, error)

GetPrivateInterfaces returns an IfAddrs that are part of RFC 6890 and have a default route. If the system can't determine its IP address or find an RFC 6890 IP address, an empty IfAddrs will be returned instead. This function is the `eval` equivalent of:

``` $ sockaddr eval -r '{{GetAllInterfaces | include "type" "ip" | include "flags" "forwardable" | include "flags" "up" | sort "default,type,size" | include "RFC" "6890" }}' / ```

func GetPublicInterfaces

func GetPublicInterfaces() (IfAddrs, error)

GetPublicInterfaces returns an IfAddrs that are NOT part of RFC 6890 and has a default route. If the system can't determine its IP address or find a non RFC 6890 IP address, an empty IfAddrs will be returned instead. This function is the `eval` equivalent of:

``` $ sockaddr eval -r '{{GetAllInterfaces | include "type" "ip" | include "flags" "forwardable" | include "flags" "up" | sort "default,type,size" | exclude "RFC" "6890" }}' / ```

func IfAddrsMath

func IfAddrsMath(operation, value string, inputIfAddrs IfAddrs) (IfAddrs, error)

IfAddrsMath will apply an IfAddrMath operation each IfAddr struct. Any failure will result in zero results.

func IfByAddress

func IfByAddress(inputRe string, ifAddrs IfAddrs) (matched, remainder IfAddrs, err error)

IfByAddress returns a list of matched and non-matched IfAddrs, or an error if the regexp fails to compile.

func IfByFlag

func IfByFlag(inputFlags string, ifAddrs IfAddrs) (matched, remainder IfAddrs, err error)

IfByFlag returns a list of matching and non-matching IfAddrs that match the specified type. For instance:

include "flag" "up,broadcast"

will include any IfAddrs that have both the "up" and "broadcast" flags set. Any addresses on those interfaces that don't match will be omitted from the results.

func IfByMaskSize

func IfByMaskSize(selectorParam string, ifAddrs IfAddrs) (matchedIfs, excludedIfs IfAddrs, err error)

IfByMaskSize returns a list of matched and non-matched IfAddrs that have the matching mask size.

func IfByName

func IfByName(inputRe string, ifAddrs IfAddrs) (matched, remainder IfAddrs, err error)

IfByName returns a list of matched and non-matched IfAddrs, or an error if the regexp fails to compile.

func IfByPort

func IfByPort(inputRe string, ifAddrs IfAddrs) (matchedIfs, excludedIfs IfAddrs, err error)

IfByPort returns a list of matched and non-matched IfAddrs, or an error if the regexp fails to compile.

func IfByRFC

func IfByRFC(selectorParam string, ifAddrs IfAddrs) (matched, remainder IfAddrs, err error)

IfByRFC returns a list of matched and non-matched IfAddrs that contain the relevant RFC-specified traits.

func IfByRFCs

func IfByRFCs(selectorParam string, ifAddrs IfAddrs) (matched, remainder IfAddrs, err error)

IfByRFCs returns a list of matched and non-matched IfAddrs that contain the relevant RFC-specified traits. Multiple RFCs can be specified and separated by the `|` symbol. No protection is taken to ensure an IfAddr does not end up in both the included and excluded list.

func IfByType

func IfByType(inputTypes string, ifAddrs IfAddrs) (matched, remainder IfAddrs, err error)

IfByType returns a list of matching and non-matching IfAddr that match the specified type. For instance:

include "type" "IPv4,IPv6"

will include any IfAddrs that is either an IPv4 or IPv6 address. Any addresses on those interfaces that don't match will be included in the remainder results.

func IncludeIfs

func IncludeIfs(selectorName, selectorParam string, inputIfAddrs IfAddrs) (IfAddrs, error)

IncludeIfs returns an IfAddrs based on the passed in selector.

func LimitIfAddrs

func LimitIfAddrs(lim uint, in IfAddrs) (IfAddrs, error)

LimitIfAddrs returns a slice of IfAddrs based on the specified limit.

func OffsetIfAddrs

func OffsetIfAddrs(off int, in IfAddrs) (IfAddrs, error)

OffsetIfAddrs returns a slice of IfAddrs based on the specified offset.

func SortIfBy

func SortIfBy(selectorParam string, inputIfAddrs IfAddrs) (IfAddrs, error)

SortIfBy returns an IfAddrs sorted based on the passed in selector. Multiple sort clauses can be passed in as a comma delimited list without whitespace.

func UniqueIfAddrsBy

func UniqueIfAddrsBy(selectorName string, inputIfAddrs IfAddrs) (IfAddrs, error)

UniqueIfAddrsBy creates a unique set of IfAddrs based on the matching selector. UniqueIfAddrsBy assumes the input has already been sorted.

func (IfAddrs) Len

func (ifs IfAddrs) Len() int

type RouteInterface

type RouteInterface interface {
	// GetDefaultInterfaceName returns the name of the interface that has a
	// default route or an error and an empty string if a problem was
	// encountered.
	GetDefaultInterfaceName() (string, error)
}

RouteInterface specifies an interface for obtaining memoized route table and network information from a given OS.

type SockAddr

type SockAddr interface {
	// CmpRFC returns 0 if SockAddr exactly matches one of the matched RFC
	// networks, -1 if the receiver is contained within the RFC network, or
	// 1 if the address is not contained within the RFC.
	CmpRFC(rfcNum uint, sa SockAddr) int

	// Contains returns true if the SockAddr arg is contained within the
	// receiver
	Contains(SockAddr) bool

	// Equal allows for the comparison of two SockAddrs
	Equal(SockAddr) bool

	DialPacketArgs() (string, string)
	DialStreamArgs() (string, string)
	ListenPacketArgs() (string, string)
	ListenStreamArgs() (string, string)

	// String returns the string representation of SockAddr
	String() string

	// Type returns the SockAddrType
	Type() SockAddrType
}

func NewSockAddr

func NewSockAddr(s string) (SockAddr, error)

New creates a new SockAddr from the string. The order in which New() attempts to construct a SockAddr is: IPv4Addr, IPv6Addr, SockAddrUnix.

NOTE: New() relies on the heuristic wherein if the path begins with either a '.' or '/' character before creating a new UnixSock. For UNIX sockets that are absolute paths or are nested within a sub-directory, this works as expected, however if the UNIX socket is contained in the current working directory, this will fail unless the path begins with "./" (e.g. "./my-local-socket"). Calls directly to NewUnixSock() do not suffer this limitation. Invalid IP addresses such as "256.0.0.0/-1" will run afoul of this heuristic and be assumed to be a valid UNIX socket path (which they are, but it is probably not what you want and you won't realize it until you stat(2) the file system to discover it doesn't exist).

type SockAddrMarshaler

type SockAddrMarshaler struct {
	SockAddr
}

Although this is pretty trivial to do in a program, having the logic here is useful all around. Note that this marshals into a *string* -- the underlying string representation of the sockaddr. If you then unmarshal into this type in Go, all will work as expected, but externally you can take what comes out and use the string value directly.

func (*SockAddrMarshaler) MarshalJSON

func (s *SockAddrMarshaler) MarshalJSON() ([]byte, error)

func (*SockAddrMarshaler) UnmarshalJSON

func (s *SockAddrMarshaler) UnmarshalJSON(in []byte) error

type SockAddrType

type SockAddrType int

func (SockAddrType) String

func (sat SockAddrType) String() string

String() for SockAddrType returns a string representation of the SockAddrType (e.g. "IPv4", "IPv6", "UNIX", "IP", or "unknown").

type SockAddrs

type SockAddrs []SockAddr

SockAddrs is a slice of SockAddrs

func (SockAddrs) FilterByType

func (sas SockAddrs) FilterByType(type_ SockAddrType) (matched, excluded SockAddrs)

FilterByType returns two lists: a list of matched and unmatched SockAddrs

func (SockAddrs) Len

func (s SockAddrs) Len() int

func (SockAddrs) Swap

func (s SockAddrs) Swap(i, j int)

type SortIPAddrsByBroadMaskLen

type SortIPAddrsByBroadMaskLen struct{ IPAddrs }

SortIPAddrsByBroadMaskLen is a type that satisfies sort.Interface and can be used by the routines in this package. The SortIPAddrsByBroadMaskLen type is used to sort IPAddrs by largest network (i.e. largest subnets first).

func (SortIPAddrsByBroadMaskLen) Less

func (s SortIPAddrsByBroadMaskLen) Less(i, j int) bool

Less reports whether the element with index i should sort before the element with index j.

type SortIPAddrsByNetworkSize

type SortIPAddrsByNetworkSize struct{ IPAddrs }

SortIPAddrsBySpecificMaskLen is a type that satisfies sort.Interface and can be used by the routines in this package. The SortIPAddrsBySpecificMaskLen type is used to sort IPAddrs by smallest network (most specific to largest network).

func (SortIPAddrsByNetworkSize) Less

func (s SortIPAddrsByNetworkSize) Less(i, j int) bool

Less reports whether the element with index i should sort before the element with index j.

type SortIPAddrsBySpecificMaskLen

type SortIPAddrsBySpecificMaskLen struct{ IPAddrs }

SortIPAddrsBySpecificMaskLen is a type that satisfies sort.Interface and can be used by the routines in this package. The SortIPAddrsBySpecificMaskLen type is used to sort IPAddrs by smallest network (most specific to largest network).

func (SortIPAddrsBySpecificMaskLen) Less

func (s SortIPAddrsBySpecificMaskLen) Less(i, j int) bool

Less reports whether the element with index i should sort before the element with index j.

type UnixSock

type UnixSock struct {
	SockAddr
	// contains filtered or unexported fields
}

func MustUnixSock

func MustUnixSock(addr string) UnixSock

MustUnixSock is a helper method that must return an UnixSock or panic on invalid input.

func NewUnixSock

func NewUnixSock(s string) (ret UnixSock, err error)

NewUnixSock creates an UnixSock from a string path. String can be in the form of either URI-based string (e.g. `file:///etc/passwd`), an absolute path (e.g. `/etc/passwd`), or a relative path (e.g. `./foo`).

func ToUnixSock

func ToUnixSock(sa SockAddr) *UnixSock

ToUnixSock returns a UnixSock type or nil if the type conversion fails.

func (UnixSock) CmpAddress

func (us UnixSock) CmpAddress(sa SockAddr) int

CmpAddress follows the Cmp() standard protocol and returns:

- -1 If the receiver should sort first because its name lexically sorts before arg - 0 if the SockAddr arg is not a UnixSock, or is a UnixSock with the same path. - 1 If the argument should sort first.

func (UnixSock) CmpRFC added in v1.0.3

func (us UnixSock) CmpRFC(rfcNum uint, sa SockAddr) int

CmpRFC doesn't make sense for a Unix socket, so just return defer decision

func (UnixSock) Contains added in v1.0.3

func (us UnixSock) Contains(sa SockAddr) bool

Contains returns true if sa and us have the same path

func (UnixSock) DialPacketArgs

func (us UnixSock) DialPacketArgs() (network, dialArgs string)

DialPacketArgs returns the arguments required to be passed to net.DialUnix() with the `unixgram` network type.

func (UnixSock) DialStreamArgs

func (us UnixSock) DialStreamArgs() (network, dialArgs string)

DialStreamArgs returns the arguments required to be passed to net.DialUnix() with the `unix` network type.

func (UnixSock) Equal

func (us UnixSock) Equal(sa SockAddr) bool

Equal returns true if a SockAddr is equal to the receiving UnixSock.

func (UnixSock) ListenPacketArgs

func (us UnixSock) ListenPacketArgs() (network, dialArgs string)

ListenPacketArgs returns the arguments required to be passed to net.ListenUnixgram() with the `unixgram` network type.

func (UnixSock) ListenStreamArgs

func (us UnixSock) ListenStreamArgs() (network, dialArgs string)

ListenStreamArgs returns the arguments required to be passed to net.ListenUnix() with the `unix` network type.

func (UnixSock) Path

func (us UnixSock) Path() string

Path returns the given path of the UnixSock

func (UnixSock) String

func (us UnixSock) String() string

String returns the path of the UnixSock

func (UnixSock) Type

func (UnixSock) Type() SockAddrType

Type is used as a type switch and returns TypeUnix

type UnixSocks

type UnixSocks []*UnixSock

Directories

Path Synopsis
cmd
Package sockaddr/template provides a text/template interface the SockAddr helper functions.
Package sockaddr/template provides a text/template interface the SockAddr helper functions.

Jump to

Keyboard shortcuts

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