Skip to content

Commit b0729da

Browse files
committed
net: add IP.IsPrivate
Add IsPrivate() helper to check if an IP is private according to RFC 1918 & RFC 4193 Fixes #29146
1 parent 04edf41 commit b0729da

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

src/net/ip.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,17 @@ func (ip IP) IsLoopback() bool {
125125
return ip.Equal(IPv6loopback)
126126
}
127127

128+
// IsPrivate reports whether ip is a private address, according to
129+
// RFC 1918 (IPv4 addresses) and RFC 4193 (IPv6 addresses).
130+
func (ip IP) IsPrivate() bool {
131+
if ip4 := ip.To4(); ip4 != nil {
132+
return ip4[0] == 10 ||
133+
(ip4[0] == 172 && ip4[1]&0xf0 == 16) ||
134+
(ip4[0] == 192 && ip4[1] == 168)
135+
}
136+
return len(ip) == IPv6len && ip[0]&0xfe == 0xfc
137+
}
138+
128139
// IsMulticast reports whether ip is a multicast address.
129140
func (ip IP) IsMulticast() bool {
130141
if ip4 := ip.To4(); ip4 != nil {

src/net/ip_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -691,6 +691,25 @@ var ipAddrScopeTests = []struct {
691691
{IP.IsGlobalUnicast, IP{0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false},
692692
{IP.IsGlobalUnicast, IP{0xff, 0x05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false},
693693
{IP.IsGlobalUnicast, nil, false},
694+
{IP.IsPrivate, nil, false},
695+
{IP.IsPrivate, IPv4(1, 1, 1, 1), false},
696+
{IP.IsPrivate, IPv4(9, 255, 255, 255), false},
697+
{IP.IsPrivate, IPv4(10, 0, 0, 0), true},
698+
{IP.IsPrivate, IPv4(10, 255, 255, 255), true},
699+
{IP.IsPrivate, IPv4(11, 0, 0, 0), false},
700+
{IP.IsPrivate, IPv4(172, 15, 255, 255), false},
701+
{IP.IsPrivate, IPv4(172, 16, 0, 0), true},
702+
{IP.IsPrivate, IPv4(172, 16, 255, 255), true},
703+
{IP.IsPrivate, IPv4(172, 32, 0, 0), false},
704+
{IP.IsPrivate, IPv4(192, 167, 255, 255), false},
705+
{IP.IsPrivate, IPv4(192, 168, 0, 0), true},
706+
{IP.IsPrivate, IPv4(192, 168, 255, 255), true},
707+
{IP.IsPrivate, IPv4(192, 169, 0, 0), false},
708+
{IP.IsPrivate, IP{0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, false},
709+
{IP.IsPrivate, IP{0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, true},
710+
{IP.IsPrivate, IP{0xfc, 0xff, 0x12, 0, 0, 0, 0, 0x44, 0, 0, 0, 0, 0, 0, 0, 0}, true},
711+
{IP.IsPrivate, IP{0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, true},
712+
{IP.IsPrivate, IP{0xfe, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false},
694713
}
695714

696715
func name(f interface{}) string {

0 commit comments

Comments
 (0)