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

Commit

Permalink
Fix NetworkAddr (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
ecbaldwin authored and HenryGessau committed Jun 26, 2019
1 parent cfefa3a commit 502ac7e
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
11 changes: 9 additions & 2 deletions net_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,10 @@ func ParseCIDR(cidr string) (net.IP, *net.IPNet, error) {

// ParseCIDRToNet is like ParseCIDR except that it only returns one *net.IPNet
// that unifies the IP address and the mask. It leaves out the network address
// which ParseCIDR returns.
// which ParseCIDR returns. This may be considered an abuse of the IPNet
// construct as it is documented that IP is supposed to be the "network
// number". However, the public IPNet interface does not dissallow it and this
// usage has been spotted in the wild.
func ParseCIDRToNet(cidr string) (*net.IPNet, error) {
ip, ipNet, err := ParseCIDR(cidr)
if err != nil {
Expand Down Expand Up @@ -79,7 +82,11 @@ func NewIP(size int) net.IP {

// NetworkAddr returns the first address in the given network, or the network address.
func NetworkAddr(n *net.IPNet) net.IP {
return n.IP
network := NewIP(len(n.IP))
for i := 0; i < len(n.IP); i++ {
network[i] = n.IP[i] & n.Mask[i]
}
return network
}

// BroadcastAddr returns the last address in the given network, or the broadcast address.
Expand Down
4 changes: 2 additions & 2 deletions net_utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func TestNetIP(t *testing.T) {

// Just a little shortcut for parsing a CIDR and get the net.IPNet.
func parse(str string) (n *net.IPNet) {
_, parsed, err := net.ParseCIDR(str)
parsed, err := ParseCIDRToNet(str)
if err == nil {
n = parsed
}
Expand Down Expand Up @@ -183,7 +183,7 @@ func TestParseCIDRErrors(t *testing.T) {

func TestNetworkAddr(t *testing.T) {
assert.Equal(t, ParseIP("203.0.113.0"), NetworkAddr(parse("203.0.113.0/24")))
assert.Equal(t, ParseIP("10.0.0.0"), NetworkAddr(parse("10.0.0.0/16")))
assert.Equal(t, ParseIP("10.0.0.0"), NetworkAddr(parse("10.0.0.29/16")))
assert.Equal(t, ParseIP("10.1.64.0"), NetworkAddr(parse("10.1.66.3/18")))

assert.Equal(t, ParseIP("2001:db8::"), NetworkAddr(parse("2001:db8::/64")))
Expand Down

0 comments on commit 502ac7e

Please sign in to comment.