iplib
packagemoduleThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
README¶
IPLib
I really enjoy Python'sipaddresslibrary and Ruby'sipaddr,I think you can write a lot of neat software if some of the little problemsaround manipulating IP addresses and netblocks are taken care of for you, so Iset out to write something like them for my language of choice, Go. This iswhat I've come up with.
IPLib is a hopefully useful,aspirationally full-featured library built around and on top of the addressprimitives found in thenet package, it seeksto make them more accessible and easier to manipulate.
It includes:
Some simple tools for performing common tasks against IP objects:
- compare two addresses
- make a copy of a net.IP address
- get the delta between two addresses
- sort
- decrement or increment addresses
- print addresses as binary or hexadecimal strings, or print their addr.ARPADNS name
- print v6 in fully expanded form
- convert between net.IP and integer values
- get the version of a v4 address or force a IPv4-mapped IPv6address to be av4 address
An enhancement ofnet.IPNet,iplib.Net is an interface with two, version-specific implementations providing features such as:
- retrieve the first and last usable address
- retrieve the wildcard mask
- enumerate all or part of a netblock to
[]net.IP - decrement or increment addresses within the boundaries of the netblock
- return the supernet of a netblock
- allocate subnets within the netblock
- return next- or previous-adjacent netblocks
The two address versions behave differently in both large and subtle ways,and the version-specific implementations seek to account for this. For examplethe Net4 implementation omits the network and broadcast addresses fromconsideration during enumeration; while the Net6 implementation introduces theconcept of a HostMask, which blocks usable addresses off from the right in thesame way that a netmask constrains them from the left
Additional version-specific considerations described in theNet4andNet6 sections below.
Sub-modules
- iana - a module for referencingIP netblocks against theInternet Assigned Numbers Authority'sSpecial IP Address Registry
- iid - a module forgenerating and validating IPv6 Interface Identifiers, includingRFC4291modified EUI64 andRFC7217Semantically Opaque addresses
Installing
go get -u github.com/c-robinson/iplibUsing iplib
There are a series of functions for working with v4 or v6net.IP objects:
package mainimport ("fmt""net""sort""github.com/c-robinson/iplib")func main() {ipa := net.ParseIP("192.168.1.1")ipb := iplib.IncrementIPBy(ipa, 15) // ipb is 192.168.1.16ipc := iplib.NextIP(ipa) // ipc is 192.168.1.2fmt.Println(iplib.CompareIPs(ipa, ipb)) // -1 fmt.Println(iplib.DeltaIP(ipa, ipb)) // 15 fmt.Println(iplib.IPToHexString(ipc)) // "c0a80102"iplist := []net.IP{ ipb, ipc, ipa }sort.Sort(iplib.ByIP(iplist)) // []net.IP{ipa, ipc, ipb}fmt.Println(iplib.IP4ToUint32(ipa)) // 3232235777fmt.Println(iplib.IPToBinaryString(ipa)) // 11000000.10101000.00000001.00000001fmt.Println(iplib.IP4ToARPA(ipa)) // 1.1.168.192.in-addr.arpa}Addresses that require or return a count default to usinguint32, which issufficient for working with the entire IPv4 space. As a rule these functionsare just lowest-common wrappers around IPv4- or IPv6-specific functions. TheIPv6-specific variants usebig.Int so they can access the entire v6 space.
The iplib.Net interface
Net describes aniplib.Net object, the exposed functions are those thatare required for comparison, sorting, generic initialization and for ancillaryfunctions such as those found in this package's submodules.
Using iplib.Net4
Net4 represents an IPv4 network. Since the first and last addresses of a v4network are typically not allocated for use these will be omitted byEnumerate(),NextIP() andPreviousIP(); they wont show up inCount();andFirstAddress() andLastAddress() show the 2nd and 2nd-to-the-lastaddresses respectively. The v4-specific methodNetworkAddress() returns thefirst address, whileBroadcastAddress() returns the last. There is anexception made forNet4 networks defined with a 31-bit netmask, since theseare assumed to be forRFC3021point-to-point links.
AdditionallyNet4 contains aWildcard() method which will return thenetwork'swildcard address.
n := iplib.NewNet4(net.ParseIP("192.168.0.0"), 16)fmt.Println(n.Count()) // 65534 (note: not 65536)fmt.Println(n.Enumerate(2, 1024)) // [192.168.4.1 192.168.4.2]fmt.Println(n.IP()) // 192.168.0.0fmt.Println(n.FirstAddress()) // 192.168.0.1fmt.Println(n.LastAddress()) // 192.168.255.254fmt.Println(n.BroadcastAddress()) // 192.168.255.255fmt.Println(n.Wildcard()) // 0000fffffmt.Println(n.Subnet(0)) // [192.168.0.0/17 192.168.128.0/17] <nil>fmt.Println(n.Supernet(0)) // 192.168.0.0/15 <nil>Using iplib.Net6
Net6 represents and IPv6 network. In some ways v6 is simpler than v4, asit does away with the special behavior of addresses at the front and back ofthe netblock. For IPv6 the primary problem is the sheer size of the thing:there are 2^128th addresses in IPv6, which translates to 340 undecillion!
n := iplib.NewNet6(net.ParseIP("2001:db8::"), 56, 0)fmt.Println(n.Count()) // 4722366482869645213696fmt.Println(n.Enumerate(2, 1024)) // [2001:db8::400 2001:db8::401]fmt.Println(n.FirstAddress()) // 2001:db8::fmt.Println(n.NextIP(n.FirstAddress())) // 2001:db8::1 <nil>fmt.Println(n.LastAddress()) // 2001:db8:0:ff:ffff:ffff:ffff:fffffmt.Println(n.Subnet(0, 0)) // [2001:db8::/57 2001:db8:0:80::/57] <nil>fmt.Println(n.Supernet(0, 0)) // 2001:db8::/55 <nil>HostMasks with Net6
To manage the address space,Net6 introducesHostMask. This optionalconstraint can be used to block addresses on the right-side of a netblocksomewhat like Netmasks do on the left.Hostmask must be specified atinitialization time and, if set, will affect the behavior ofCount(),Enumerate(),LastAddress(),NextIP() andPreviousIP().Subnet() andSupernet() generate objects that inherit the hostmask of their parent, whilea hostmask must be specified forNextNet() andPreviousNet().
// this is the same as the previous example, except with a hostmask setn := NewNet6(net.ParseIP("2001:db8::"), 56, 60)fmt.Println(n.Count()) // 4096fmt.Println(n.Enumerate(2, 1024)) // [2001:db8:0:40:: 2001:db8:0:40:100::]fmt.Println(n.FirstAddress()) // 2001:db8::fmt.Println(n.NextIP(n.FirstAddress())) // 2001:db8:0:0:100:: <nil>fmt.Println(n.LastAddress()) // 2001:db8:0:ff:f00::fmt.Println(n.Mask().String()) // ffffffffffffff000000000000000000fmt.Println(n.Hostmask.String()) // 0000000000000000f0fffffffffffffffmt.Println(n.Subnet(0, 60)) // [2001:db8::/57 2001:db8:0:80::/57] <nil>fmt.Println(n.Supernet(0, 60)) // 2001:db8::/55 <nil>
Documentation¶
Overview¶
Package iplib provides enhanced tools for working with IP networks andaddresses. These tools are built upon and extend the generic functionalityfound in the Go "net" package.
The main library comes in two parts: a series of utilities for working withnet.IP (sort, increment, decrement, delta, compare, convert to binary or hex-string, convert between net.IP and integer) and an enhancement of net.IPNetcalled iplib.Net that can calculate the first and last IPs of a block as wellas enumerating the block into []net.IP, incrementing and decrementing withinthe boundaries of the block and creating sub- or super-nets of it.
For most features iplib exposes a v4 and a v6 variant to handle each networkproperly, but in all cases there is a generic function that handles any IP androutes between them. One caveat to this is those functions that require orreturn an integer value representing the address, in these cases the IPv4variants take an int32 as input while the IPv6 functions require a *big.Intin order to work with the 128bits of address.
For managing the complexity of IPv6 address-spaces, this library adds a newmask, called a Hostmask, as an optional constraint on iplib.Net6 networks,please see the type-documentation for more information on using it.
For functions where it is possible to exceed the address-space the rule isthat underflows return the version-appropriate all-zeroes address whileoverflows return the all-ones.
There are also two submodules under iplib: the iplib/iid module containsfunctions for generatingRFC 7217-compliant IPv6 Interface ID addresses, andiplib/iana imports the IANA IP Special Registries and exposes functions forcomparing IP addresses against those registries to determine if the IP is partof a special reservation (for exampleRFC 1918 private networks or theRFC3849 documentation network).
Index¶
- Constants
- Variables
- func BigintToIP6(z *big.Int) net.IP
- func CompareIPs(a, b net.IP) int
- func CompareNets(a, b Net) int
- func CopyIP(ip net.IP) net.IP
- func DecrementIP4By(ip net.IP, count uint32) net.IP
- func DecrementIP6By(ip net.IP, count *big.Int) net.IP
- func DecrementIP6WithinHostmask(ip net.IP, hm HostMask, count *big.Int) (net.IP, error)
- func DecrementIPBy(ip net.IP, count uint32) net.IP
- func DeltaIP(a, b net.IP) uint32
- func DeltaIP4(a, b net.IP) uint32
- func DeltaIP6(a, b net.IP) *big.Int
- func EffectiveVersion(ip net.IP) int
- func ExpandIP6(ip net.IP) string
- func ForceIP4(ip net.IP) net.IP
- func HexStringToIP(s string) net.IP
- func IP4ToARPA(ip net.IP) string
- func IP4ToUint32(ip net.IP) uint32
- func IP6ToARPA(ip net.IP) string
- func IP6ToUint64(ip net.IP) uint64
- func IPToARPA(ip net.IP) string
- func IPToBigint(ip net.IP) *big.Int
- func IPToBinaryString(ip net.IP) string
- func IPToHexString(ip net.IP) string
- func IncrementIP4By(ip net.IP, count uint32) net.IP
- func IncrementIP6By(ip net.IP, count *big.Int) net.IP
- func IncrementIP6WithinHostmask(ip net.IP, hm HostMask, count *big.Int) (net.IP, error)
- func IncrementIPBy(ip net.IP, count uint32) net.IP
- func Is4in6(ip net.IP) bool
- func IsAllOnes(ip net.IP) bool
- func IsAllZeroes(ip net.IP) bool
- func NextIP(ip net.IP) net.IP
- func NextIP6WithinHostmask(ip net.IP, hm HostMask) (net.IP, error)
- func PreviousIP(ip net.IP) net.IP
- func PreviousIP6WithinHostmask(ip net.IP, hm HostMask) (net.IP, error)
- func Uint32ToIP4(i uint32) net.IP
- func Uint64ToIP6(i uint64) net.IP
- func Version(ip net.IP) int
- type ByIP
- type ByNet
- type HostMask
- type Net
- type Net4
- func (n Net4) BroadcastAddress() net.IP
- func (n Net4) Contains(ip net.IP) bool
- func (n Net4) ContainsNet(network Net) bool
- func (n Net4) Count() uint32
- func (n Net4) Enumerate(size, offset int) []net.IP
- func (n Net4) FirstAddress() net.IP
- func (n Net4) IP() net.IP
- func (n Net4) Is4in6() bool
- func (n Net4) LastAddress() net.IP
- func (n Net4) Mask() net.IPMask
- func (n Net4) NetworkAddress() net.IP
- func (n Net4) NextIP(ip net.IP) (net.IP, error)
- func (n Net4) NextNet(masklen int) Net4
- func (n Net4) PreviousIP(ip net.IP) (net.IP, error)
- func (n Net4) PreviousNet(masklen int) Net4
- func (n Net4) RandomIP() net.IP
- func (n Net4) String() string
- func (n Net4) Subnet(masklen int) ([]Net4, error)
- func (n Net4) Supernet(masklen int) (Net4, error)
- func (n Net4) Version() int
- func (n Net4) Wildcard() net.IPMask
- type Net6
- func (n Net6) Contains(ip net.IP) bool
- func (n Net6) ContainsNet(network Net) bool
- func (n Net6) Controls(ip net.IP) bool
- func (n Net6) Count() *big.Int
- func (n Net6) Enumerate(size, offset int) []net.IP
- func (n Net6) FirstAddress() net.IP
- func (n Net6) IP() net.IP
- func (n Net6) LastAddress() net.IP
- func (n Net6) Mask() net.IPMask
- func (n Net6) NextIP(ip net.IP) (net.IP, error)
- func (n Net6) NextNet(masklen int) Net6
- func (n Net6) PreviousIP(ip net.IP) (net.IP, error)
- func (n Net6) PreviousNet(masklen int) Net6
- func (n Net6) RandomIP() net.IP
- func (n Net6) String() string
- func (n Net6) Subnet(netmasklen, hostmasklen int) ([]Net6, error)
- func (n Net6) Supernet(netmasklen, hostmasklen int) (Net6, error)
- func (n Net6) Version() int
Examples¶
- BigintToIP6
- CompareIPs
- DecrementIP4By
- DecrementIP6By
- DecrementIP6WithinHostmask
- DeltaIP4
- DeltaIP6
- EffectiveVersion
- ExpandIP6
- ForceIP4
- HexStringToIP
- IP4ToARPA
- IP4ToUint32
- IP6ToARPA
- IPToBinaryString
- IPToHexString
- IncrementIP4By
- IncrementIP6By
- IncrementIP6WithinHostmask
- Net4.Contains
- Net4.ContainsNet
- Net4.Count
- Net4.Enumerate
- Net4.NextNet
- Net4.PreviousNet
- Net4.Subnet
- Net4.Supernet
- Net4.Wildcard
- Net6.Contains
- Net6.Count
- Net6.LastAddress
- Net6.NextIP
- Net6.NextNet
- Net6.PreviousIP
- Net6.PreviousNet
- Net6.Subnet
- Net6.Supernet
- NextIP
- NextIP6WithinHostmask
- PreviousIP
- PreviousIP6WithinHostmask
- Uint32ToIP4
- Version
Constants¶
const (// MaxIPv4 is the max size of a uint32, also the IPv4 address spaceMaxIPv4uint32 = 1<<32 - 1// IP4Version is the label returned by IPv4 addressesIP4Version = 4// IP6Version is the label returned by IPv6 addressesIP6Version = 6)
Variables¶
var (ErrAddressOutOfRange =errors.New("address is not a part of this netblock")ErrBadMaskLength =errors.New("illegal mask length provided")ErrBroadcastAddress =errors.New("address is the broadcast address of this netblock (and not considered usable)")ErrNetworkAddress =errors.New("address is the network address of this netblock (and not considered usable)")ErrNoValidRange =errors.New("no netblock can be found between the supplied values"))
Errors that may be returned by functions in this package
Functions¶
funcBigintToIP6¶
BigintToIP6 converts a big.Int to an ip6 address and returns it as a net.IP
Example¶
z := big.Int{}z.SetString("42540766452641154071740215577757643572", 10)fmt.Println(BigintToIP6(&z))Output:2001:db8:85a3::8a2e:370:7334
funcCompareIPs¶
CompareIPs is just a thin wrapper around bytes.Compare, but is here forcompleteness as this is a good way to compare two IP objects. Since it usesbytes.Compare the return value is identical: 0 if a==b, -1 if a<b, 1 if a>b
Example¶
fmt.Println(CompareIPs(net.ParseIP("192.168.1.0"), net.ParseIP("192.168.1.1")))fmt.Println(CompareIPs(net.ParseIP("10.0.0.0"), net.ParseIP("10.0.0.0")))fmt.Println(CompareIPs(net.ParseIP("2001:db8::100"), net.ParseIP("2001:db8::99")))Output:-101
funcCompareNets¶
CompareNets compares two iplib.Net objects by evaluating their networkaddress (the first address in a CIDR range) and, if they're equal,comparing their netmasks (smallest wins). This means that if a network iscompared to one of its subnets, the enclosing network sorts first.
funcCopyIP¶added inv1.0.6
CopyIP creates a new net.IP object containing the same data as the suppliednet.IP (e.g. creates a new array and duplicates the contents)
funcDecrementIP4By¶
DecrementIP4By returns a v4 net.IP that is lower than the supplied net.IPby the supplied integer value. If you underflow the IP space it will return0.0.0.0
Example¶
ip := net.ParseIP("192.168.2.0")fmt.Println(DecrementIP4By(ip, 255))Output:192.168.1.1
funcDecrementIP6By¶
DecrementIP6By returns a net.IP that is lower than the supplied net.IP bythe supplied integer value. If you underflow the IP space it will return::
Example¶
z := big.NewInt(16777215)ip := net.ParseIP("2001:db8::ffff:ffff")fmt.Println(DecrementIP6By(ip, z))Output:2001:db8::ff00:0
funcDecrementIP6WithinHostmask¶added inv1.0.0
DecrementIP6WithinHostmask returns a net.IP that is less than the unmaskedportion of the supplied net.IP by the supplied integer value. If theinput or output value fall outside the boundaries of the hostmask aErrAddressOutOfRange will be returned
Example¶
ip := net.ParseIP("2001:db8:1000::")ip1, _ := DecrementIP6WithinHostmask(ip, NewHostMask(0), big.NewInt(1))ip2, _ := DecrementIP6WithinHostmask(ip, NewHostMask(56), big.NewInt(1))fmt.Println(ip1)fmt.Println(ip2)Output:2001:db8:fff:ffff:ffff:ffff:ffff:ffff2001:db8:fff:ffff:ff00::
funcDecrementIPBy¶
DecrementIPBy returns a net.IP that is lower than the supplied net.IP bythe supplied integer value. If you underflow the IP space it will returnthe zero address.
funcDeltaIP¶
DeltaIP takes two net.IP's as input and returns the difference between themup to the limit of uint32.
funcDeltaIP4¶
DeltaIP4 takes two net.IP's as input and returns a total of the number ofaddresses between them, up to the limit of uint32.
Example¶
ipa := net.ParseIP("192.168.1.1")ipb := net.ParseIP("192.168.2.0")fmt.Println(DeltaIP4(ipa, ipb))Output:255
funcDeltaIP6¶
DeltaIP6 takes two net.IP's as input and returns a total of the number ofaddressed between them as a big.Int. It will technically work on v4 as wellbut is considerably slower than DeltaIP4.
Example¶
ipa := net.ParseIP("2001:db8::ffff:ffff")ipb := net.ParseIP("2001:db8::ff00:0")fmt.Println(DeltaIP6(ipa, ipb))Output:16777215
funcEffectiveVersion¶
EffectiveVersion returns 4 if the net.IP either contains a v4 address or ifit contains the v4-encapsulating v6 address range ::ffff. Note that thesecond example below is a v6 address but reports as v4 because it is in the4in6 block. This mirrors how Go's `net` package would treat the address
Example¶
fmt.Println(EffectiveVersion(net.ParseIP("192.168.1.1")))fmt.Println(EffectiveVersion(net.ParseIP("::ffff:c0a8:101")))fmt.Println(EffectiveVersion(net.ParseIP("2001:db8::c0a8:101")))Output:446
funcExpandIP6¶
ExpandIP6 takes a net.IP containing an IPv6 address and returns a string ofthe address fully expanded
Example¶
fmt.Println(ExpandIP6(net.ParseIP("2001:db8::1")))Output:2001:0db8:0000:0000:0000:0000:0000:0001
funcForceIP4¶
ForceIP4 takes a net.IP containing an RFC4291 IPv4-mapped IPv6 address andreturns only the encapsulated v4 address.
Example¶
fmt.Println(len(ForceIP4(net.ParseIP("::ffff:c0a8:101"))))Output:4
funcHexStringToIP¶
HexStringToIP converts a hexadecimal string to an IP address. If the givenstring cannot be converted nil is returned. Input strings may contain '.'or ':'
Example¶
ip := HexStringToIP("c0a80101")fmt.Println(ip.String())Output:192.168.1.1
funcIP4ToARPA¶added inv0.2.0
IP4ToARPA takes a net.IP containing an IPv4 address and returns a string ofthe address represented as dotted-decimals in reverse-order and followed bythe IPv4 ARPA domain "in-addr.arpa"
Example¶
fmt.Println(IP4ToARPA(net.ParseIP("192.168.1.1")))Output:1.1.168.192.in-addr.arpa
funcIP4ToUint32¶
IP4ToUint32 converts a net.IPv4 to a uint32.
Example¶
fmt.Println(IP4ToUint32(net.ParseIP("192.168.1.1")))Output:3232235777
funcIP6ToARPA¶added inv0.2.0
IP6ToARPA takes a net.IP containing an IPv6 address and returns a string ofthe address represented as a sequence of 4-bit nibbles in reverse order andfollowed by the IPv6 ARPA domain "ip6.arpa"
Example¶
fmt.Println(IP6ToARPA(net.ParseIP("2001:db8::ffff:ffff")))Output:f.f.f.f.f.f.f.f.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa
funcIP6ToUint64¶added inv1.0.0
IP6ToUint64 converts a net.IPv6 to a uint64, but only the first 64bits ofaddress are considered meaningful (any information in the last 64bits willbe lost). To work with entire IPv6 addresses use IPToBigint()
funcIPToARPA¶added inv0.2.0
IPToARPA takes a net.IP as input and returns a string of the version-appropriate ARPA DNS name
funcIPToBinaryString¶added inv0.2.0
IPToBinaryString returns the given net.IP as a binary string
Example¶
fmt.Println(IPToBinaryString(net.ParseIP("192.168.1.1")))fmt.Println(IPToBinaryString(net.ParseIP("2001:db8::ffff:ffff")))Output:11000000.10101000.00000001.0000000100100000.00000001.00001101.10111000.00000000.00000000.00000000.00000000.00000000.00000000.00000000.00000000.11111111.11111111.11111111.11111111
funcIPToHexString¶
IPToHexString returns the given net.IP as a hexadecimal string. This is thedefault stringer format for v6 net.IP
Example¶
fmt.Println(IPToHexString(net.ParseIP("192.168.1.1")))Output:c0a80101
funcIncrementIP4By¶
IncrementIP4By returns a v4 net.IP that is greater than the suppliednet.IP by the supplied integer value. If you overflow the IP space itwill return 255.255.255.255
Example¶
ip := net.ParseIP("192.168.1.1")fmt.Println(IncrementIP4By(ip, 255))Output:192.168.2.0
funcIncrementIP6By¶
IncrementIP6By returns a net.IP that is greater than the supplied net.IP bythe supplied integer value. If you overflow the IP space it will return the(meaningless in this context) all-ones address
Example¶
z := big.NewInt(16777215)ip := net.ParseIP("2001:db8::ff00:0")fmt.Println(IncrementIP6By(ip, z))Output:2001:db8::ffff:ffff
funcIncrementIP6WithinHostmask¶added inv1.0.0
IncrementIP6WithinHostmask returns a net.IP that is greater than theunmasked portion of the supplied net.IP by the supplied integer value. Ifthe input or output value fall outside the boundaries of the hostmask aErrAddressOutOfRange will be returned
Example¶
ip := net.ParseIP("2001:db8:1000::")ip1, _ := IncrementIP6WithinHostmask(ip, NewHostMask(0), big.NewInt(1))ip2, _ := IncrementIP6WithinHostmask(ip, NewHostMask(56), big.NewInt(1))fmt.Println(ip1)fmt.Println(ip2)Output:2001:db8:1000::12001:db8:1000:0:100::
funcIncrementIPBy¶
IncrementIPBy returns a net.IP that is greater than the supplied net.IP bythe supplied integer value. If you overflow the IP space it will returnthe all-ones address
funcIs4in6¶added inv1.0.0
Is4in6 returns true if the supplied net.IP is an IPv4 address encapsulatedin an IPv6 address. It is very common for the net library to re-write v4addresses into v6 addresses prefixed 0000:0000:0000:0000:ffff. When thishappens net.IP will have a 16-byte array but always return a v4 address (infact there is no way to force it to behave as a v6 address), which has leadto many confused message board comments
funcIsAllOnes¶added inv1.0.0
IsAllOnes returns true if the supplied net.IP is the all-ones address,if given a 4-in-6 address this function will treat it as IPv4
funcIsAllZeroes¶added inv1.0.0
IsAllZeroes returns true if the supplied net.IP is the all-zero address, ifgiven a 4-in-6 address this function will treat it as IPv4
funcNextIP¶
NextIP returns a net.IP incremented by one from the input address. Thisfunction is roughly as fast for v4 as IncrementIP4By(1) but is consistently4x faster on v6 than IncrementIP6By(1). The bundled tests providebenchmarks doing so, as well as iterating over the entire v4 address space.
Example¶
fmt.Println(NextIP(net.ParseIP("192.168.1.1")))fmt.Println(NextIP(net.ParseIP("2001:db8::ffff:fffe")))Output:192.168.1.22001:db8::ffff:ffff
funcNextIP6WithinHostmask¶added inv1.0.0
NextIP6WithinHostmask takes a net.IP and Hostmask as arguments and attemptsto increment the IP by one, within the boundary of the hostmask. If bitsinside the hostmask are set, an empty net.IP{} and an ErrAddressOutOfRangewill be returned
Example¶
ip, _ := NextIP6WithinHostmask(net.ParseIP("2001:db8:1234:5678::"), NewHostMask(56))fmt.Println(ip)Output:2001:db8:1234:5678:100::
funcPreviousIP¶added inv0.2.0
PreviousIP returns a net.IP decremented by one from the input address. Thisfunction is roughly as fast for v4 as DecrementIP4By(1) but is consistently4x faster on v6 than DecrementIP6By(1). The bundled tests providebenchmarks doing so, as well as iterating over the entire v4 address space.
Example¶
fmt.Println(PreviousIP(net.ParseIP("192.168.1.2")))fmt.Println(PreviousIP(net.ParseIP("2001:db8::ffff:ffff")))Output:192.168.1.12001:db8::ffff:fffe
funcPreviousIP6WithinHostmask¶added inv1.0.0
PreviousIP6WithinHostmask takes a net.IP and Hostmask as arguments andattempts to decrement the IP by one, within the boundary of the hostmask.If bits inside the hostmask are set, an empty net.IP{} and anErrAddressOutOfRange will be returned
Example¶
ip, _ := PreviousIP6WithinHostmask(net.ParseIP("2001:db8:1234:5678::"), NewHostMask(56))fmt.Println(ip)Output:2001:db8:1234:5677:ff00::
funcUint32ToIP4¶
Uint32ToIP4 converts a uint32 to an ip4 address and returns it as a net.IP
Example¶
fmt.Println(Uint32ToIP4(3232235777))
Output:192.168.1.1
funcUint64ToIP6¶added inv1.0.0
Uint64ToIP6 converts a uint64 to an IPv6 address, but only the left-mosthalf of a (128bit) IPv6 address can be accessed in this way, the back halfof the address is lost. To manipulate the entire address, see BigintToIP6()
funcVersion¶
Version returns 4 if the net.IP contains a v4 address. It will return 6 forany v6 address, including the v4-encapsulating v6 address range ::ffff.Contrast with EffectiveVersion above and note that in the provided exampleForceIP4() is used because, by default, net.ParseIP() stores IPv4 addressesas 4in6 encapsulating v6 addresses. One consequence of which is thatit is impossible to use a 4in6 address as a v6 address
Example¶
fmt.Println(Version(ForceIP4(net.ParseIP("192.168.1.1"))))fmt.Println(Version(net.ParseIP("::ffff:c0a8:101")))fmt.Println(Version(net.ParseIP("2001:db8::c0a8:101")))Output:466
Types¶
typeByIP¶
ByIP implements sort.Interface for net.IP addresses
typeByNet¶
type ByNet []Net
ByNet implements sort.Interface for iplib.Net based on thestarting address of the netblock, with the netmask as a tie breaker. So iftwo Networks are submitted and one is a subset of the other, the enclosingnetwork will be returned first.
typeHostMask¶added inv1.0.0
type HostMask []byte
HostMask is a mask that can be applied to IPv6 addresses to mask out bitsfrom the right side of the address instead of the left (which is thepurview of a netmask), the intended use-case is for situations where thereis a desire to reserve a portion of the address for some other purpose andonly allow iplib to manage the remainder. A concrete example would beIPv6 Interface Identifiers as described in RFC4291, RFC4941 or RFC7217 inwhich the final 64bits of the address are used to construct a unique hostidentifier and the allocator only has control of the first 64bits. So thenext IP from 2001:db8:1234:5678:: would be 2001:db8:1234:5679 instead of2001:db8:1234:5678::1. Here is a Net6 object eing initialized without ahostmask:
n := NewNet6(2001:db8::, 56, 0)Address 2001:db8::Netmask ffff:ffff:ffff:ff00:0000:0000:0000:0000Hostmask 0000:0000:0000:0000:0000:0000:0000:0000First 2001:0db8:0000:0000:0000:0000:0000:0000Last 2001:0db8:0000:00ff:ffff:ffff:ffff:ffffCount 4722366482869645213696
This creates a block with 4.7 sextillion usable addresses. Below is he sameblock with a hostmask of /60. The mask is applied from the rightmost byte,leaving 12 unmasked bits for a total of 4096 allocatable addresses:
n:= NewNet6(2001:db8::, 56, 60)Address 2001:db8::Netmask ffff:ffff:ffff:ff00:0000:0000:0000:0000Hostmask 0000:0000:0000:0000:0fff:ffff:ffff:ffffFirst 2001:0db8:0000:0000:0000:0000:0000:0000Last 2001:0db8:0000:00ff:f000:0000:0000:0000Count 4096
In the first example the second IP address of the netblock is 2001:db8::1,in the second example it is 2001:db8:0:1::
One important note: even though bytes are filled in from the right the bitswithin those bytes are still blocked out left-to-right, so that addressincrementing/decrementing makes sense to the end user, as shown here:
BINARY Base16 Base10 Example Max16 Max100000 0000 0x00 0 /56 0xFF 2551000 0000 0x80 128 /57 0x7F 1271100 0000 0xC0 192 /58 0x3F 631110 0000 0xE0 224 /59 0x1F 311111 0000 0xF0 240 /60 0x0F 151111 1000 0xF8 248 /61 0x07 71111 1100 0xFC 252 /62 0x03 31111 1110 0xFE 254 /63 0x01 1
A hostmask of /1 will block out the left-most bit of the 16th bytewhile a /8 will block the entire 16th byte.
To initialize a hostmask you must give it an integer value between 1 and128, which represent the number of bits in the mask.
funcNewHostMask¶added inv1.0.0
NewHostMask returns a HostMask initialized to masklen
func (HostMask)BoundaryByte¶added inv1.0.0
BoundaryByte returns the rightmost byte in the mask in which any bits fallinside the hostmask, as well as the position of that byte. For example amasklength of 58 would return "0xc0, 8" while 32 would return "0xff, 12".If the hostmask is unset "0x00, -1" will be returned
typeNet¶
type Net interface {Contains(ipnet.IP)boolContainsNet(networkNet)boolFirstAddress()net.IPIP()net.IPLastAddress()net.IPMask()net.IPMaskString()stringVersion()int}Net describes an iplib.Net object, the enumerated functions are those thatare required for comparison, sorting, generic initialization and forancillary functions such as those found in the iid and iana submodules
funcNewNet¶
NewNet returns a new Net object containing ip at the specified masklen. Inthe Net6 case the hostbits value will be set to 0. If the masklen is setto an insane value (greater than 32 for IPv4 or 128 for IPv6) an empty Netwill be returned
funcNewNetBetween¶
NewNetBetween takes two net.IP's as input and will return the largestnetblock that can fit between them (exclusive of the IP's themselves).If there is an exact fit it will set a boolean to true, otherwise the boolwill be false. If no fit can be found (probably because a >= b) anErrNoValidRange will be returned.
funcParseCIDR¶
ParseCIDR returns a new Net object. It is a passthrough to net.ParseCIDRand will return any error it generates to the caller. There is one majordifference between how net.IPNet manages addresses and how ipnet.Net does,and this function exposes it: net.ParseCIDR *always* returns an IPv6address; if given a v4 address it returns the RFC4291 IPv4-mapped IPv6address internally, but treats it like v4 in practice. In contrastiplib.ParseCIDR will re-encode it as a v4
typeNet4¶added inv1.0.0
Net4 is an implementation of Net intended for IPv4 netblocks. It hasfunctions to return the broadcast address and wildcard mask not present inthe IPv6 implementation
funcNet4FromStr¶added inv1.0.0
Net4FromStr takes a string which should be a v4 address in CIDR notationand returns an initialized Net4. If the string isn't parseable an emptyNet4 will be returned
funcNewNet4¶added inv1.0.0
NewNet4 returns an initialized Net4 object at the specified masklen. Ifmask is greater than 32, or if a v6 address is supplied, an empty Net4will be returned
func (Net4)BroadcastAddress¶added inv1.0.0
BroadcastAddress returns the broadcast address for the represented network.In the context of IPv6 broadcast is meaningless and the value will beequivalent to LastAddress().
func (Net4)Contains¶added inv1.0.0
Contains returns true if ip is contained in the represented netblock
Example¶
n := NewNet4(net.ParseIP("192.168.1.0"), 24)fmt.Println(n.Contains(net.ParseIP("192.168.1.111")))fmt.Println(n.Contains(net.ParseIP("10.14.0.1")))Output:truefalse
func (Net4)ContainsNet¶added inv1.0.0
ContainsNet returns true if the given Net is contained within therepresented block
Example¶
n1 := NewNet4(net.ParseIP("192.168.0.0"), 16)n2 := NewNet4(net.ParseIP("192.168.1.0"), 24)fmt.Println(n1.ContainsNet(n2))fmt.Println(n2.ContainsNet(n1))Output:truefalse
func (Net4)Count¶added inv1.0.0
Count returns the total number of usable IP addresses in the representednetwork..
Example¶
n := NewNet4(net.ParseIP("192.168.0.0"), 16)fmt.Println(n.Count())Output:65534
func (Net4)Enumerate¶added inv1.0.0
Enumerate generates an array of all usable addresses in Net up to thegiven size starting at the given offset. If size=0 the entire block isenumerated.
NOTE: RFC3021 defines a use case for netblocks of /31 for use in point-to-point links. For this reason enumerating networks at these lengths willreturn a 2-element array even though it would naturally return none.
For consistency, enumerating a /32 will return the IP in a 1 element array
Example¶
n := NewNet4(net.ParseIP("192.168.0.0"), 16)fmt.Println(n.Enumerate(2, 100))Output:[192.168.0.101 192.168.0.102]
func (Net4)FirstAddress¶added inv1.0.0
FirstAddress returns the first usable address for the represented network
func (Net4)IP¶added inv1.0.0
IP returns the network address for the represented network, e.g.the lowest IP address in the given block
func (Net4)Is4in6¶added inv1.0.0
Is4in6 will return true if this Net4 object or any of its parents wereexplicitly initialized with a 4in6 address (::ffff:xxxx.xxx)
func (Net4)LastAddress¶added inv1.0.0
LastAddress returns the last usable address for the represented network
func (Net4)NetworkAddress¶added inv1.0.0
NetworkAddress returns the network address for the represented network, e.g.the lowest IP address in the given block
func (Net4)NextIP¶added inv1.0.0
NextIP takes a net.IP as an argument and attempts to increment it by one.If the resulting address is outside of the range of the represented networkit will return an empty net.IP and an ErrAddressOutOfRange. If the resultis the broadcast address, the address _will_ be returned, but so will anErrBroadcastAddress, to indicate that the address is technicallyoutside the usable scope
func (Net4)NextNet¶added inv1.0.0
NextNet takes a CIDR mask-size as an argument and attempts to create a newNet object just after the current Net, at the requested mask length
Example¶
n := NewNet4(net.ParseIP("192.168.1.0"), 24)fmt.Println(n.NextNet(24))Output:192.168.2.0/24
func (Net4)PreviousIP¶added inv1.0.0
PreviousIP takes a net.IP as an argument and attempts to decrement it byone. If the resulting address is outside of the range of the representednetwork it will return an empty net.IP and an ErrAddressOutOfRange. If theresult is the network address, the address _will_ be returned, but so willan ErrNetworkAddress, to indicate that the address is technically outsidethe usable scope
func (Net4)PreviousNet¶added inv1.0.0
PreviousNet takes a CIDR mask-size as an argument and creates a new Netobject just before the current one, at the requested mask length. If thespecified mask is for a larger network than the current one then the newnetwork may encompass the current one, e.g.:
iplib.Net{192.168.4.0/22}.Subnet(21) -> 192.168.0.0/21
In the above case 192.168.4.0/22 is part of 192.168.0.0/21
Example¶
n := NewNet4(net.ParseIP("192.168.1.0"), 24)fmt.Println(n.PreviousNet(24))Output:192.168.0.0/24
func (Net4)RandomIP¶added inv1.0.6
RandomIP returns a random address from this Net4. It uses crypto/rand and*big.Int so is not the most performant implementation possible
func (Net4)String¶added inv1.0.0
String returns the CIDR notation of the enclosed network e.g. 192.168.0.1/24
func (Net4)Subnet¶added inv1.0.0
Subnet takes a CIDR mask-size as an argument and carves the current Netobject into subnets of that size, returning them as a []Net. The maskprovided must be a larger-integer than the current mask. If set to 0 Subnetwill carve the network in half
Example¶
n := NewNet4(net.ParseIP("192.168.0.0"), 16)sub, _ := n.Subnet(17)fmt.Println(sub)Output:[192.168.0.0/17 192.168.128.0/17]
func (Net4)Supernet¶added inv1.0.0
Supernet takes a CIDR mask-size as an argument and returns a Net objectcontaining the supernet of the current Net at the requested mask length.The mask provided must be a smaller-integer than the current mask. If setto 0 Supernet will return the next-largest network
Examples:Net{192.168.1.0/24}.Supernet(0) -> Net{192.168.0.0/23}Net{192.168.1.0/24}.Supernet(22) -> Net{Net{192.168.0.0/22}
Example¶
n := NewNet4(net.ParseIP("192.168.1.0"), 24)n2, _ := n.Supernet(22)fmt.Println(n2)Output:192.168.0.0/22
typeNet6¶added inv1.0.0
Net6 is an implementation of Net that supports IPv6 operations. Toinitialize a Net6 you must supply a network address and mask prefix aswith Net4, but you may also optionally supply an integer value between0 and 128 that Net6 will mask out from the right, via a HostMask (see thedocumentation for HostMask in this library). If "0" HostMask will beignored. The sum of netmask prefix and hostmask must be less than 128.
Hostmask affects Count, Enumerate, LastAddress, NextIP and PreviousIP; italso affects NextNet and PreviousNet which will inherit the hostmask fromtheir parent. Subnet and Supernet both require a hostmask in their functioncalls
funcNet6FromStr¶added inv1.0.0
Net6FromStr takes a string which should be a v6 address in CIDR notationand returns an initialized Net6. If the string isn't parseable an emptyNet6 will be returned
funcNewNet6¶added inv1.0.0
NewNet6 returns an initialized Net6 object at the specified netmasklen withthe specified hostmasklen. If netmasklen or hostmasklen is greater than 128it will return an empty object; it will also return an empty object if thesum of the two masks is 128 or greater. If a v4 address is supplied itwill be treated as a RFC4291 v6-encapsulated-v4 network (which is thedefault behavior for net.IP)
func (Net6)Contains¶added inv1.0.0
Contains returns true if ip is contained in the represented netblock
Example¶
n := NewNet6(net.ParseIP("2001:db8:1234:5678::"), 64, 0)fmt.Println(n.Contains(net.ParseIP("2001:db8:1234:5678::1")))fmt.Println(n.Contains(net.ParseIP("2001:db8:1234::")))Output:truefalse
func (Net6)ContainsNet¶added inv1.0.0
ContainsNet returns true if the given Net is contained within therepresented block
func (Net6)Controls¶added inv1.0.0
Controls returns true if ip is within the scope of the represented block,meaning that it is both inside of the netmask and outside of the hostmask.In other words this function will return true if ip would be enumerated bythis Net6 instance
func (Net6)Count¶added inv1.0.0
Count returns the number of IP addresses in the represented netblock
Example¶
// without hostmaskn := NewNet6(net.ParseIP("2001:db8:1234:5678::"), 64, 0)fmt.Println(n.Count())// with hostmask set to 56, leaving 8 usable bytes between the two masksn = NewNet6(net.ParseIP("2001:db8:1234:5678::"), 64, 56)fmt.Println(n.Count())Output:18446744073709551616256
func (Net6)Enumerate¶added inv1.0.0
Enumerate generates an array of all usable addresses in Net up to thegiven size starting at the given offset, so long as the result is less thanMaxUint32. If size=0 the entire block is enumerated (again, so long as theresult is less than MaxUint32).
For consistency, enumerating a /128 will return the IP in a 1 element array
func (Net6)FirstAddress¶added inv1.0.0
FirstAddress returns the first usable address for the represented network
func (Net6)IP¶added inv1.0.0
IP returns the network address for the represented network, e.g.the lowest IP address in the given block
func (Net6)LastAddress¶added inv1.0.0
LastAddress returns the last usable address for the represented network
Example¶
// without hostmaskn := NewNet6(net.ParseIP("2001:db8:1234:5678::"), 64, 0)fmt.Println(n.LastAddress())// with hostmask set to 56, leaving 8 usable bytes between the two masksn = NewNet6(net.ParseIP("2001:db8:1234:5678::"), 64, 56)fmt.Println(n.LastAddress())Output:2001:db8:1234:5678:ffff:ffff:ffff:ffff2001:db8:1234:5678:ff00::
func (Net6)NextIP¶added inv1.0.0
NextIP takes a net.IP as an argument and attempts to increment it by onewithin the boundary of allocated network-bytes. If the resulting address isoutside of the range of the represented network it will return an emptynet.IP and an ErrAddressOutOfRange
Example¶
// without hostmaskn := NewNet6(net.ParseIP("2001:db8:1234:5678::"), 64, 0)fmt.Println(n.NextIP(net.ParseIP("2001:db8:1234:5678::")))// with hostmask set to 56, leaving 8 usable bytes between the two masksn = NewNet6(net.ParseIP("2001:db8:1234:5678::"), 64, 56)fmt.Println(n.NextIP(net.ParseIP("2001:db8:1234:5678::")))// as above, but trying to scan past the end of the netblockfmt.Println(n.NextIP(net.ParseIP("2001:db8:1234:5678:ff00::")))Output:2001:db8:1234:5678::1 <nil>2001:db8:1234:5678:100:: <nil><nil> address is not a part of this netblock
func (Net6)NextNet¶added inv1.0.0
NextNet takes a CIDR mask-size as an argument and attempts to create a newNet object just after the current Net, at the requested mask length andwith the same hostmask as the current Net
Example¶
n := NewNet6(net.ParseIP("2001:db8:1234:5678::"), 64, 0)fmt.Println(n.NextNet(0))Output:2001:db8:1234:5679::/64
func (Net6)PreviousIP¶added inv1.0.0
PreviousIP takes a net.IP as an argument and attempts to decrement it byone within the boundary of the allocated network-bytes. If the resultingaddress is outside the range of the represented netblock it will return anempty net.IP and an ErrAddressOutOfRange
Example¶
// without hostmaskn := NewNet6(net.ParseIP("2001:db8:1234:5678::"), 64, 0)fmt.Println(n.PreviousIP(net.ParseIP("2001:db8:1234:5678:ff00::")))// as above, but trying to scan past the end of the netblockfmt.Println(n.PreviousIP(net.ParseIP("2001:db8:1234:5678::")))// with hostmask set to 56, leaving 8 usable bytes between the two masksn = NewNet6(net.ParseIP("2001:db8:1234:5678::"), 64, 56)fmt.Println(n.PreviousIP(net.ParseIP("2001:db8:1234:5678:ff00::")))Output:2001:db8:1234:5678:feff:ffff:ffff:ffff <nil><nil> address is not a part of this netblock2001:db8:1234:5678:fe00:: <nil>
func (Net6)PreviousNet¶added inv1.0.0
PreviousNet takes a CIDR mask-size as an argument and creates a new Netobject just before the current one, at the requested mask length. If thespecified mask is for a larger network than the current one then the newnetwork may encompass the current one
Example¶
n := NewNet6(net.ParseIP("2001:db8:1234:5678::"), 64, 0)// at the same netmaskfmt.Println(n.PreviousNet(0))// at a larger netmask (result encompasses the starting network)fmt.Println(n.PreviousNet(62))Output:2001:db8:1234:5677::/642001:db8:1234:5674::/62
func (Net6)RandomIP¶added inv1.0.6
RandomIP returns a random address from this Net6. It uses crypto/rand andso is not the most performant implementation possible
func (Net6)String¶added inv1.0.0
String returns the CIDR notation of the enclosed network e.g. 2001:db8::/16
func (Net6)Subnet¶added inv1.0.0
Subnet takes a CIDR mask-size as an argument and carves the current Netobject into subnets of that size, returning them as a []Net. The maskprovided must be a larger-integer than the current mask. If set to 0 Subnetwill carve the network in half. Hostmask must be provided if desired
Example¶
n := NewNet6(net.ParseIP("2001:db8:1234:5678::"), 64, 0)for _, i := range []int{65, 66} {sub, _ := n.Subnet(i, 0)fmt.Println(sub)}Output:[2001:db8:1234:5678::/65 2001:db8:1234:5678:8000::/65][2001:db8:1234:5678::/66 2001:db8:1234:5678:4000::/66 2001:db8:1234:5678:8000::/66 2001:db8:1234:5678:c000::/66]
func (Net6)Supernet¶added inv1.0.0
Supernet takes a CIDR mask-size as an argument and returns a Net objectcontaining the supernet of the current Net at the requested mask length.The mask provided must be a smaller-integer than the current mask. If setto 0 Supernet will return the next-largest network
Example¶
n := NewNet6(net.ParseIP("2001:db8:1234:5678::"), 64, 0)fmt.Println(n.Supernet(0, 0))Output:2001:db8:1234:5678::/63 <nil>
Directories¶
| Path | Synopsis |
|---|---|
Package iana imports the Internet Assigned Numbers Authority (IANA) IP Special Registries as a data structure and implements functions to compare the reserved networks against iplib.Net objects. | Package iana imports the Internet Assigned Numbers Authority (IANA) IP Special Registries as a data structure and implements functions to compare the reserved networks against iplib.Net objects. |
Package iid provides functions for generating and validating IPv6 Interface Identifiers (IID's). | Package iid provides functions for generating and validating IPv6 Interface Identifiers (IID's). |