We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent a10b4cf commit 424bea4Copy full SHA for 424bea4
src/net/ip.go
@@ -130,6 +130,19 @@ func (ip IP) IsMulticast() bool {
130
return len(ip) == IPv6len && ip[0] == 0xff
131
}
132
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
+
146
// IsInterfaceLocalMulticast reports whether ip is
147
// an interface-local multicast address.
148
func (ip IP) IsInterfaceLocalMulticast() bool {
src/net/ip_test.go
@@ -666,6 +666,15 @@ var ipAddrScopeTests = []struct {
666
{IP.IsMulticast, IP{0xff, 0x05, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, true},
667
{IP.IsMulticast, IP{0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, false},
668
{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},
678
{IP.IsInterfaceLocalMulticast, IPv4(224, 0, 0, 0), false},
679
{IP.IsInterfaceLocalMulticast, IPv4(0xff, 0x01, 0, 0), false},
680
{IP.IsInterfaceLocalMulticast, IPv6interfacelocalallnodes, true},
0 commit comments