Skip to content

Commit 424bea4

Browse files
committed
net: add IP.IsLocal
Fixes golang#29146 Change-Id: I69f51f943a684bdffaa9a32bea56eb2c5d881b33
1 parent a10b4cf commit 424bea4

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

src/net/ip.go

+13
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,19 @@ func (ip IP) IsMulticast() bool {
130130
return len(ip) == IPv6len && ip[0] == 0xff
131131
}
132132

133+
// IsLocal reports whether `ip' is a local address, according to
134+
// RFC 1918 (IPv4 addresses) and RFC 4193 (IPv6 addresses).
135+
func (ip IP) IsLocal() bool {
136+
if ip4 := ip.To4(); ip4 != nil {
137+
// Local IPv4 addresses are defined in https://tools.ietf.org/html/rfc1918
138+
return ip4[0] == 10 ||
139+
(ip4[0] == 172 && ip4[1]&0xf0 == 16) ||
140+
(ip4[0] == 192 && ip4[1] == 168)
141+
}
142+
// Local IPv6 addresses are defined in https://tools.ietf.org/html/rfc4193
143+
return len(ip) == IPv6len && ip[0]&0xfe == 0xfc
144+
}
145+
133146
// IsInterfaceLocalMulticast reports whether ip is
134147
// an interface-local multicast address.
135148
func (ip IP) IsInterfaceLocalMulticast() bool {

src/net/ip_test.go

+9
Original file line numberDiff line numberDiff line change
@@ -666,6 +666,15 @@ var ipAddrScopeTests = []struct {
666666
{IP.IsMulticast, IP{0xff, 0x05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, true},
667667
{IP.IsMulticast, IP{0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false},
668668
{IP.IsMulticast, nil, false},
669+
{IP.IsLocal, nil, false},
670+
{IP.IsLocal, IPv4(10, 0, 0, 0), true},
671+
{IP.IsLocal, IPv4(11, 0, 0, 0), false},
672+
{IP.IsLocal, IPv4(172, 16, 0, 0), true},
673+
{IP.IsLocal, IPv4(172, 32, 0, 0), false},
674+
{IP.IsLocal, IPv4(192, 168, 0, 0), true},
675+
{IP.IsLocal, IPv4(192, 169, 0, 0), false},
676+
{IP.IsLocal, IP{0xfc, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, true},
677+
{IP.IsLocal, IP{0xff, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false},
669678
{IP.IsInterfaceLocalMulticast, IPv4(224, 0, 0, 0), false},
670679
{IP.IsInterfaceLocalMulticast, IPv4(0xff, 0x01, 0, 0), false},
671680
{IP.IsInterfaceLocalMulticast, IPv6interfacelocalallnodes, true},

0 commit comments

Comments
 (0)