Skip to content

Commit

Permalink
net: add IP.IsPrivate
Browse files Browse the repository at this point in the history
Add IsPrivate() helper to check if an IP is private according to RFC 1918 & RFC 4193

Fixes golang#29146
  • Loading branch information
6543 committed Feb 16, 2021
1 parent f0d23c9 commit 29178a0
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/net/ip.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,17 @@ func (ip IP) IsLoopback() bool {
return ip.Equal(IPv6loopback)
}

// IsPrivate reports whether ip is a private address, according to
// RFC 1918 (IPv4 addresses) and RFC 4193 (IPv6 addresses).
func (ip IP) IsPrivate() bool {
if ip4 := ip.To4(); ip4 != nil {
return ip4[0] == 10 ||
(ip4[0] == 172 && ip4[1]&0xf0 == 16) ||
(ip4[0] == 192 && ip4[1] == 168)
}
return len(ip) == IPv6len && ip[0]&0xfe == 0xfc
}

// IsMulticast reports whether ip is a multicast address.
func (ip IP) IsMulticast() bool {
if ip4 := ip.To4(); ip4 != nil {
Expand Down
19 changes: 19 additions & 0 deletions src/net/ip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -690,6 +690,25 @@ var ipAddrScopeTests = []struct {
{IP.IsGlobalUnicast, IP{0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false},
{IP.IsGlobalUnicast, IP{0xff, 0x05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false},
{IP.IsGlobalUnicast, nil, false},
{IP.IsPrivate, nil, false},
{IP.IsPrivate, IPv4(1, 1, 1, 1), false},
{IP.IsPrivate, IPv4(9, 255, 255, 255), false},
{IP.IsPrivate, IPv4(10, 0, 0, 0), true},
{IP.IsPrivate, IPv4(10, 255, 255, 255), true},
{IP.IsPrivate, IPv4(11, 0, 0, 0), false},
{IP.IsPrivate, IPv4(172, 15, 255, 255), false},
{IP.IsPrivate, IPv4(172, 16, 0, 0), true},
{IP.IsPrivate, IPv4(172, 16, 255, 255), true},
{IP.IsPrivate, IPv4(172, 32, 0, 0), false},
{IP.IsPrivate, IPv4(192, 167, 255, 255), false},
{IP.IsPrivate, IPv4(192, 168, 0, 0), true},
{IP.IsPrivate, IPv4(192, 168, 255, 255), true},
{IP.IsPrivate, IPv4(192, 169, 0, 0), false},
{IP.IsPrivate, IP{0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, false},
{IP.IsPrivate, IP{0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, true},
{IP.IsPrivate, IP{0xfc, 0xff, 0x12, 0, 0, 0, 0, 0x44, 0, 0, 0, 0, 0, 0, 0, 0}, true},
{IP.IsPrivate, IP{0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, true},
{IP.IsPrivate, IP{0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false},
}

func name(f interface{}) string {
Expand Down

0 comments on commit 29178a0

Please sign in to comment.