Skip to content

Commit

Permalink
net: add IP.IsLocal
Browse files Browse the repository at this point in the history
Fixes golang#29146

Change-Id: I69f51f943a684bdffaa9a32bea56eb2c5d881b33
  • Loading branch information
MaxSem committed Feb 17, 2019
1 parent a10b4cf commit 424bea4
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/net/ip.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,19 @@ func (ip IP) IsMulticast() bool {
return len(ip) == IPv6len && ip[0] == 0xff
}

// IsLocal reports whether `ip' is a local address, according to
// RFC 1918 (IPv4 addresses) and RFC 4193 (IPv6 addresses).
func (ip IP) IsLocal() bool {
if ip4 := ip.To4(); ip4 != nil {
// Local IPv4 addresses are defined in https://tools.ietf.org/html/rfc1918
return ip4[0] == 10 ||
(ip4[0] == 172 && ip4[1]&0xf0 == 16) ||
(ip4[0] == 192 && ip4[1] == 168)
}
// Local IPv6 addresses are defined in https://tools.ietf.org/html/rfc4193
return len(ip) == IPv6len && ip[0]&0xfe == 0xfc
}

// IsInterfaceLocalMulticast reports whether ip is
// an interface-local multicast address.
func (ip IP) IsInterfaceLocalMulticast() bool {
Expand Down
9 changes: 9 additions & 0 deletions src/net/ip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -666,6 +666,15 @@ var ipAddrScopeTests = []struct {
{IP.IsMulticast, IP{0xff, 0x05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, true},
{IP.IsMulticast, IP{0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false},
{IP.IsMulticast, nil, false},
{IP.IsLocal, nil, false},
{IP.IsLocal, IPv4(10, 0, 0, 0), true},
{IP.IsLocal, IPv4(11, 0, 0, 0), false},
{IP.IsLocal, IPv4(172, 16, 0, 0), true},
{IP.IsLocal, IPv4(172, 32, 0, 0), false},
{IP.IsLocal, IPv4(192, 168, 0, 0), true},
{IP.IsLocal, IPv4(192, 169, 0, 0), false},
{IP.IsLocal, IP{0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, true},
{IP.IsLocal, IP{0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false},
{IP.IsInterfaceLocalMulticast, IPv4(224, 0, 0, 0), false},
{IP.IsInterfaceLocalMulticast, IPv4(0xff, 0x01, 0, 0), false},
{IP.IsInterfaceLocalMulticast, IPv6interfacelocalallnodes, true},
Expand Down

0 comments on commit 424bea4

Please sign in to comment.