Giter VIP home page Giter VIP logo

iplib's Introduction

IPLib

Documentation Go Report Card Tests

ATTENTION version 2.0.0 is a breaking change from previous versions for handling IPv6 addresses (functions for IPv4 are unchanged). Calls that result in arithmatic operations against IPv6 now use uint128.Uint128 instead of *big.Int. Until now this library restricted itself to using the standard library, but math/big is sloooooooooow and the performance gains from switching were too large to ignore:

Benchmark *big.Int uint128.Uint128
Benchmark_DeltaIP6 79.27 ns/op 2.809 ns/op
BenchmarkDecrementIP6By 50.54 ns/op 13.88 ns/op
BenchmarkIncrementIP6By 50.48 ns/op 13.92 ns/op
BenchmarkNet_Count6 122.2 ns/op 11.26 ns/op

It would be fantastic to remove this external dependency in some future v3 that switched to a native uint128 but for that to happen this proposal (or something similar) would need to be adopted.

Okay you can stop paying attention now

I really enjoy Python's ipaddress library and Ruby's ipaddr, I think you can write a lot of neat software if some of the little problems around manipulating IP addresses and netblocks are taken care of for you, so I set out to write something like them for my language of choice, Go. This is what I've come up with.

IPLib is a hopefully useful, aspirationally full-featured library built around and on top of the address primitives found in the net package, it seeks to 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.ARPA DNS 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 a v4 address
iplib.Net

An enhancement of net.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 example the Net4 implementation omits the network and broadcast addresses from consideration during enumeration; while the Net6 implementation introduces the concept of a HostMask, which blocks usable addresses off from the right in the same way that a netmask constrains them from the left

Additional version-specific considerations described in the Net4 and Net6 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 v6 net.IP objects:

package main

import (
	"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.16
	ipc := iplib.NextIP(ipa)                 // ipc is 192.168.1.2

	fmt.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))      // 3232235777
	fmt.Println(iplib.IPToBinaryString(ipa)) // 11000000.10101000.00000001.00000001
	fmt.Println(iplib.IP4ToARPA(ipa))        // 1.1.168.192.in-addr.arpa
}

Addresses that require or return a count default to using uint32, which is sufficient for working with the entire IPv4 space. As a rule these functions are just lowest-common wrappers around IPv4- or IPv6-specific functions. The IPv6-specific variants use uint128.Uint128 so they can access the entire v6 space.

The iplib.Net interface

Net describes an iplib.Net object, the exposed functions are those that are required for comparison, sorting, generic initialization and for ancillary functions 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 v4 network are typically not allocated for use these will be omitted by Enumerate(), NextIP() and PreviousIP(); they wont show up in Count(); and FirstAddress() and LastAddress() show the 2nd and 2nd-to-the-last addresses respectively. The v4-specific method NetworkAddress() returns the first address, while BroadcastAddress() returns the last. There is an exception made for Net4 networks defined with a 31-bit netmask, since these are assumed to be for RFC3021 point-to-point links.

Additionally Net4 contains a Wildcard() method which will return the network's wildcard 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.0
fmt.Println(n.FirstAddress())     // 192.168.0.1
fmt.Println(n.LastAddress())      // 192.168.255.254
fmt.Println(n.BroadcastAddress()) // 192.168.255.255
fmt.Println(n.Wildcard())         // 0000ffff
fmt.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, as it does away with the special behavior of addresses at the front and back of the 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())                  // 4722366482869645213696
fmt.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:ffff
fmt.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 introduces HostMask. This optional constraint can be used to block addresses on the right-side of a netblock somewhat like Netmasks do on the left. Hostmask must be specified at initialization time and, if set, will affect the behavior of Count(), Enumerate(), LastAddress(), NextIP() and PreviousIP(). Subnet() and Supernet() generate objects that inherit the hostmask of their parent, while a hostmask must be specified for NextNet() and PreviousNet().

// this is the same as the previous example, except with a hostmask set
n := NewNet6(net.ParseIP("2001:db8::"), 56, 60)
fmt.Println(n.Count())                  // 4096
fmt.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())          // ffffffffffffff000000000000000000
fmt.Println(n.Hostmask.String())        // 0000000000000000f0ffffffffffffff
fmt.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 I wrote to test many of the features within this library and might be useful in evaluating it.

iplib's People

Contributors

0xd61 avatar c-robinson avatar luisdavim avatar pic4xiu avatar ryanfolsom avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

iplib's Issues

Incorrect Example Using iplib.Net4

Hi,

I found incorrect dos in readme file related to using iplib.Net4. In this line:

n := NewNet4(net.ParseIP("192.168.0.0"), 16)

it should be:

n := iplib.NewNet4(net.ParseIP("192.168.0.0"), 16)

and in this one:

fmt.Println(n.Network()) // 192.168.0.0

it should be:

fmt.Println(n.IP()) // 192.168.0.0

NextNet seems to return the wrong value

See this example:

package main

import (
	"fmt"

	"github.com/c-robinson/iplib"
)

func GetNextSubnet(lastCIDR string, nextSize int) {
	lastNet := iplib.Net4FromStr(lastCIDR)

	if nextSize == 0 {
		nextSize, _ = lastNet.Mask().Size()
	}
	nextNet := lastNet.NextNet(nextSize)
	fmt.Printf("Next net: %s\n", nextNet)
}

func main() {
	GetNextSubnet("10.80.6.0/24", 18)
}

Outputs:

Next net: 10.80.0.0/18

Am I doing something wrong?

If I use the same subnet size, I get an expected result

GetNextSubnet("10.80.6.0/24", 0) // 0 default to the same size

output:

Next net: 10.80.7.0/24

and with:

GetNextSubnet("10.80.6.0/24", 22)

it goes backwards?

Next net: 10.80.4.0/22

Integer overflow on 32bit targets

This line causes an integer overflow when compiling for arm.

iplib/net6.go

Line 337 in d4ce4cb

sizes := []int{math.MaxUint32}

The solution would be to use uint32 instead of int for the datatype.

The error message is:
vendor/github.com/c-robinson/iplib/net6.go:337:21: constant 4294967295 overflows int

test suite issue on 32-bit archs: cannot use MaxIPv4 (untyped int constant 4294967295) as int value in argument to t.Errorf (overflows)

Hi,

I'm packaging your software for Debian (as a build-dependency for https://www.crowdsec.net/) and I'm seeing the following test failure on 32-bit archs (e.g. armel, armhf, i386 as seen on https://ci.debian.net/packages/g/golang-github-c-robinson-iplib/):

   dh_auto_test -O--builddirectory=_build -O--buildsystem=golang
	cd _build && go test -vet=off -v -p 32 github.com/c-robinson/iplib github.com/c-robinson/iplib/iana github.com/c-robinson/iplib/iid
# github.com/c-robinson/iplib [github.com/c-robinson/iplib.test]
src/github.com/c-robinson/iplib/iplib_test.go:362:30: cannot use MaxIPv4 (untyped int constant 4294967295) as int value in argument to t.Errorf (overflows)
FAIL	github.com/c-robinson/iplib [build failed]

It can be trivially reproduced in an i386 chroot on an amd64 machine.

Casting the constant explicitly to uint in that error message does the trick, but maybe it should or could have been declared a uint32 in the first place? That being said, I don't know anything about Go, so I'll just mention the patch I'm considering applying to iplib_test.go in the Debian package until I've gotten some feedback here:

-               t.Errorf("want %d got %d", MaxIPv4, i)
+               t.Errorf("want %d got %d", uint(MaxIPv4), i)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.