Skip to content
This repository has been archived by the owner on Jul 22, 2024. It is now read-only.

Commit

Permalink
add IPv4 implementation that returns a 4-byte address (#21)
Browse files Browse the repository at this point in the history
* add IPv4 implementation that returns a 4-byte address

* add IPv4Net returning 4-byte IPNet with given prefix len
  • Loading branch information
ecbaldwin authored May 15, 2021
1 parent 26d9747 commit 0671efb
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
20 changes: 20 additions & 0 deletions net_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -285,3 +285,23 @@ func IPMax(a, b net.IP) net.IP {
}
return a
}

// IPv4 returns the IP address (in 4-byte form) of the
// IPv4 address a.b.c.d.
func IPv4(a, b, c, d byte) net.IP {
p := make(net.IP, net.IPv4len)
p[0] = a
p[1] = b
p[2] = c
p[3] = d
return p
}

// IPv4Net returns the IPNet (in 4-byte form) of the
// IPv4 address a.b.c.d/p.
func IPv4Net(a, b, c, d byte, p int) net.IPNet {
return net.IPNet{
IP: IPv4(a, b, c, d),
Mask: net.CIDRMask(p, 8*net.IPv4len),
}
}
9 changes: 9 additions & 0 deletions net_utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -260,3 +260,12 @@ func TestIPLessThan(t *testing.T) {
"2001:43::"+
"]", fmt.Sprintf("%s", ips))
}

func TestIPv4(t *testing.T) {
assert.Equal(t, ParseIP("127.0.0.1"), IPv4(127, 0, 0, 1))
}

func TestIPv4Net(t *testing.T) {
lo, _ := ParseCIDRToNet("127.0.0.1/8")
assert.Equal(t, *lo, IPv4Net(127, 0, 0, 1, 8))
}

0 comments on commit 0671efb

Please sign in to comment.