Movatterモバイル変換


[0]ホーム

URL:


iplib

packagemodule
v2.0.5Latest Latest
Warning

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

Go to latest
Published: Apr 6, 2024 License:MITImports:13Imported by:6

Details

Repository

github.com/c-robinson/iplib

Links

README

IPLib

DocumentationGo Report CardTests

ATTENTION version 2.0.0 is a breaking change from previous versions forhandling IPv6 addresses (functions for IPv4 are unchanged). Calls that resultin arithmatic operations against IPv6 now useuint128.Uint128instead of*big.Int. Until now this library restricted itself to using thestandard library, butmath/big is sloooooooooow and the performance gainsfrom switching were too large to ignore:

Benchmark*big.Intuint128.Uint128
Benchmark_DeltaIP679.27 ns/op2.809 ns/op
BenchmarkDecrementIP6By50.54 ns/op13.88 ns/op
BenchmarkIncrementIP6By50.48 ns/op13.92 ns/op
BenchmarkNet_Count6122.2 ns/op11.26 ns/op

It would be fantastic to remove this external dependency in some future v3that switched to a nativeuint128 but for that to happenthis proposal(or something similar) would need to be adopted.

Okay you can stop paying attention now

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:

net.IP tools

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
iplib.Net

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
Net4 and Net6 implementations of Net

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

Installing

go get -u github.com/c-robinson/iplib/v2

Using 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/v2")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 useuint128.Uint128 so they can access the entire v6space.

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 an 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>

Test driving

IPfool is a simple command-line tool that Iwrote to test many of the features within this library and might be useful inevaluating it.

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 int32 as input while the IPv6 functions require uint128.Uint128in 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

Examples

Constants

View Source
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

View Source
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

funcARPAToIP

func ARPAToIP(sstring)net.IP

ARPAToIP takes a strings containing an ARPA domain and returns thecorresponding net.IP

funcARPAToIP4

func ARPAToIP4(sstring)net.IP

ARPAToIP4 takes a string containing an IPv4 ARPA domain and returns thecorresponding net.IP

funcARPAToIP6

func ARPAToIP6(sstring)net.IP

ARPAToIP6 takes a string containing an IPv6 ARPA domain and returns thecorresponding net.IP

funcBigintToIP6

func BigintToIP6(z *big.Int)net.IP

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

func CompareIPs(a, bnet.IP)int

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

func CompareNets(a, bNet)int

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

func CopyIP(ipnet.IP)net.IP

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

func DecrementIP4By(ipnet.IP, countuint32)net.IP

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

func DecrementIP6By(ipnet.IP, countuint128.Uint128)net.IP

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 := uint128.New(16777215, 0)ip := net.ParseIP("2001:db8::ffff:ffff")fmt.Println(DecrementIP6By(ip, z))
Output:2001:db8::ff00:0

funcDecrementIP6WithinHostmask

func DecrementIP6WithinHostmask(ipnet.IP, hmHostMask, countuint128.Uint128) (net.IP,error)

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), uint128.New(1, 0))ip2, _ := DecrementIP6WithinHostmask(ip, NewHostMask(56), uint128.New(1, 0))fmt.Println(ip1)fmt.Println(ip2)
Output:2001:db8:fff:ffff:ffff:ffff:ffff:ffff2001:db8:fff:ffff:ff00::

funcDecrementIPBy

func DecrementIPBy(ipnet.IP, countuint32)net.IP

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

func DeltaIP(a, bnet.IP)uint32

DeltaIP takes two net.IP's as input and returns the difference between themup to the limit of uint32.

funcDeltaIP4

func DeltaIP4(a, bnet.IP)uint32

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

func DeltaIP6(a, bnet.IP)uint128.Uint128

DeltaIP6 takes two net.IP's as input and returns a total of the number ofaddressed between them as uint128.Uint128 . It will technically work on v4as well

Example
ipa := net.ParseIP("2001:db8::ffff:ffff")ipb := net.ParseIP("2001:db8::ff00:0")fmt.Println(DeltaIP6(ipa, ipb))
Output:16777215

funcEffectiveVersion

func EffectiveVersion(ipnet.IP)int

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

func ExpandIP6(ipnet.IP)string

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

func ForceIP4(ipnet.IP)net.IP

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

func HexStringToIP(sstring)net.IP

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

func IP4ToARPA(ipnet.IP)string

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

func IP4ToUint32(ipnet.IP)uint32

IP4ToUint32 converts a net.IPv4 to a uint32

Example
fmt.Println(IP4ToUint32(net.ParseIP("192.168.1.1")))
Output:3232235777

funcIP6ToARPA

func IP6ToARPA(ipnet.IP)string

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

funcIP6ToUint128

func IP6ToUint128(ipnet.IP)uint128.Uint128

IP6ToUint128 converts a net.IPv6 to a uint128.Uint128

Example
fmt.Println(IP6ToUint128(net.ParseIP("2001:db8:85a3::8a2e:370:7334")))
Output:42540766452641154071740215577757643572

funcIP6ToUint64

func IP6ToUint64(ipnet.IP)uint64

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 IP6ToUint128()

funcIPToARPA

func IPToARPA(ipnet.IP)string

IPToARPA takes a net.IP as input and returns a string of the version-appropriate ARPA DNS name

funcIPToBigint

func IPToBigint(ipnet.IP) *big.Int

IPToBigint converts a net.IP to big.Int.

Example
fmt.Println(IPToBigint(net.ParseIP("2001:db8:85a3::8a2e:370:7334")))
Output:42540766452641154071740215577757643572

funcIPToBinarySliceadded inv2.0.5

func IPToBinarySlice(ipnet.IP) []byte

IPToBinarySlice returns the given net.IP as a []byte whosevalues are the binary representation of the IP

funcIPToBinaryString

func IPToBinaryString(ipnet.IP)string

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

func IPToHexString(ipnet.IP)string

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

func IncrementIP4By(ipnet.IP, countuint32)net.IP

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

func IncrementIP6By(ipnet.IP, countuint128.Uint128)net.IP

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 := uint128.New(16777215, 0)ip := net.ParseIP("2001:db8::ff00:0")fmt.Println(IncrementIP6By(ip, z))
Output:2001:db8::ffff:ffff

funcIncrementIP6WithinHostmask

func IncrementIP6WithinHostmask(ipnet.IP, hmHostMask, countuint128.Uint128) (net.IP,error)

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), uint128.New(1, 0))ip2, _ := IncrementIP6WithinHostmask(ip, NewHostMask(56), uint128.New(1, 0))fmt.Println(ip1)fmt.Println(ip2)
Output:2001:db8:1000::12001:db8:1000:0:100::

funcIncrementIPBy

func IncrementIPBy(ipnet.IP, countuint32)net.IP

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

func Is4in6(ipnet.IP)bool

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

func IsAllOnes(ipnet.IP)bool

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

func IsAllZeroes(ipnet.IP)bool

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

func NextIP(ipnet.IP)net.IP

NextIP returns a net.IP incremented by one from the input address

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

func NextIP6WithinHostmask(ipnet.IP, hmHostMask) (net.IP,error)

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

func PreviousIP(ipnet.IP)net.IP

PreviousIP returns a net.IP decremented by one from the input address

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

func PreviousIP6WithinHostmask(ipnet.IP, hmHostMask) (net.IP,error)

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::

funcUint128ToIP6

func Uint128ToIP6(iuint128.Uint128)net.IP

Uint128ToIP6 converts a uint128 to an IPv6 address and returns it as anet.IP

Example
z, _ := uint128.FromString("42540766452641154071740215577757643572")fmt.Println(Uint128ToIP6(z))
Output:2001:db8:85a3::8a2e:370:7334

funcUint32ToIP4

func Uint32ToIP4(iuint32)net.IP

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

func Uint64ToIP6(iuint64)net.IP

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

func Version(ipnet.IP)int

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

type ByIP []net.IP

ByIP implements sort.Interface for net.IP addresses

func (ByIP)Len

func (biByIP) Len()int

Len implements sort.interface Len(), returning the length of theByIP array

func (ByIP)Less

func (biByIP) Less(a, bint)bool

Less implements sort.interface Less(), given two elements in the array itreturns true if the LHS should sort before the RHS. For details on theimplementation, see CompareIPs()

func (ByIP)Swap

func (biByIP) Swap(a, bint)

Swap implements sort.interface Swap(), swapping two elements in our array

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.

func (ByNet)Len

func (bnByNet) Len()int

Len implements sort.interface Len(), returning the length of theByNetwork array

func (ByNet)Less

func (bnByNet) Less(a, bint)bool

Less implements sort.interface Less(), given two elements in the array itreturns true if the LHS should sort before the RHS. For details on theimplementation, see CompareNets()

func (ByNet)Swap

func (bnByNet) Swap(a, bint)

Swap implements sort.interface Swap(), swapping two elements in our array

typeHostMask

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 being 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

func NewHostMask(masklenint)HostMask

NewHostMask returns a HostMask initialized to masklen

func (HostMask)BoundaryByte

func (mHostMask) BoundaryByte() (byte,int)

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

func (HostMask)Size

func (mHostMask) Size() (int,int)

Size returns the number of ones and total bits in the mask

func (HostMask)String

func (mHostMask) String()string

String returns the hexadecimal form of m, with no punctuation

typeNet

type Net interface {Contains(ipnet.IP)boolContainsNet(networkNet)boolFirstAddress()net.IPIP()net.IPLastAddress()net.IPMask()net.IPMaskString()stringVersion()int// contains filtered or unexported methods}

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

funcAllNetsBetweenadded inv2.0.3

func AllNetsBetween(a, bnet.IP) ([]Net,error)

AllNetsBetween takes two net.IPs as input and will return a slice ofnetblocks spanning the range between them, inclusively, even if it mustreturn one or more single-address netblocks to do so

funcNewNet

func NewNet(ipnet.IP, masklenint)Net

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

func NewNetBetween(a, bnet.IP) (Net,bool,error)

NewNetBetween takes two net.IP's as input and will return the largestnetblock that can fit between them inclusive of at least the first address.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

func ParseCIDR(sstring) (net.IP,Net,error)

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

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

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

func Net4FromStr(sstring)Net4

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

func NewNet4(ipnet.IP, masklenint)Net4

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

func (nNet4) BroadcastAddress()net.IP

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

func (nNet4) Contains(ipnet.IP)bool

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

func (nNet4) ContainsNet(networkNet)bool

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

func (nNet4) Count()uint32

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

func (nNet4) Enumerate(size, offsetint) []net.IP

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

func (nNet4) FirstAddress()net.IP

FirstAddress returns the first usable address for the represented network

func (Net4)IP

func (nNet4) IP()net.IP

IP returns the network address for the represented network, e.g.the lowest IP address in the given block

func (Net4)Is4in6

func (nNet4) Is4in6()bool

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

func (nNet4) LastAddress()net.IP

LastAddress returns the last usable address for the represented network

func (Net4)Mask

func (nNet4) Mask()net.IPMask

Mask returns the netmask of the netblock

func (Net4)NetworkAddress

func (nNet4) NetworkAddress()net.IP

NetworkAddress returns the network address for the represented network, e.g.the lowest IP address in the given block

func (Net4)NextIP

func (nNet4) NextIP(ipnet.IP) (net.IP,error)

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

func (nNet4) NextNet(masklenint)Net4

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

func (nNet4) PreviousIP(ipnet.IP) (net.IP,error)

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

func (nNet4) PreviousNet(masklenint)Net4

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

func (nNet4) RandomIP()net.IP

RandomIP returns a random address from this Net4

func (Net4)String

func (nNet4) String()string

String returns the CIDR notation of the enclosed network e.g. 192.168.0.1/24

func (Net4)Subnet

func (nNet4) Subnet(masklenint) ([]Net4,error)

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

func (nNet4) Supernet(masklenint) (Net4,error)

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

func (Net4)Version

func (nNet4) Version()int

Version returns the version of IP for the enclosed netblock, 4 in this case

func (Net4)Wildcard

func (nNet4) Wildcard()net.IPMask

Wildcard will return the wildcard mask for a given netmask

Example
n := NewNet4(net.ParseIP("192.168.0.0"), 16)fmt.Println(n.Wildcard())
Output:0000ffff

typeNet6

type Net6 struct {net.IPNetHostmaskHostMask}

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

func Net6FromStr(sstring)Net6

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

func NewNet6(ipnet.IP, netmasklen, hostmasklenint)Net6

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

func (nNet6) Contains(ipnet.IP)bool

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

func (nNet6) ContainsNet(networkNet)bool

ContainsNet returns true if the given Net is contained within therepresented block

func (Net6)Controls

func (nNet6) Controls(ipnet.IP)bool

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

func (nNet6) Count()uint128.Uint128

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

func (nNet6) Enumerate(size, offsetint) []net.IP

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

func (nNet6) FirstAddress()net.IP

FirstAddress returns the first usable address for the represented network

func (Net6)IP

func (nNet6) IP()net.IP

IP returns the network address for the represented network, e.g.the lowest IP address in the given block

func (Net6)LastAddress

func (nNet6) LastAddress()net.IP

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

func (nNet6) Mask()net.IPMask

Mask returns the netmask of the netblock

func (Net6)NextIP

func (nNet6) NextIP(ipnet.IP) (net.IP,error)

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

func (nNet6) NextNet(masklenint)Net6

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

func (nNet6) PreviousIP(ipnet.IP) (net.IP,error)

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

func (nNet6) PreviousNet(masklenint)Net6

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

func (nNet6) RandomIP()net.IP

RandomIP returns a random address from this Net6. It uses crypto/rand andso is not the most performant implementation possible

func (Net6)String

func (nNet6) String()string

String returns the CIDR notation of the enclosed network e.g. 2001:db8::/16

func (Net6)Subnet

func (nNet6) Subnet(netmasklen, hostmasklenint) ([]Net6,error)

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

func (nNet6) Supernet(netmasklen, hostmasklenint) (Net6,error)

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>

func (Net6)Version

func (nNet6) Version()int

Version returns the version of IP for the enclosed netblock as an int. 6in this case

Source Files

View all Source files

Directories

PathSynopsis
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).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp