Skip to content

Commit 0425819

Browse files
committed
use the new multiaddr utilities in IsPublicAddr/IsPrivateAddr
This now means that addresses must *start* with the an IP address, we won't just pull one out of the middle.
1 parent 7b43167 commit 0425819

File tree

1 file changed

+33
-24
lines changed

1 file changed

+33
-24
lines changed

private.go

Lines changed: 33 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -67,36 +67,45 @@ func parseCIDR(cidrs []string) []*net.IPNet {
6767

6868
// IsPublicAddr retruns true if the IP part of the multiaddr is a publicly routable address
6969
func IsPublicAddr(a ma.Multiaddr) bool {
70-
ip, err := a.ValueForProtocol(ma.P_IP4)
71-
if err == nil {
72-
return !inAddrRange(ip, Private4) && !inAddrRange(ip, Unroutable4)
73-
}
74-
75-
ip, err = a.ValueForProtocol(ma.P_IP6)
76-
if err == nil {
77-
return !inAddrRange(ip, Private6) && !inAddrRange(ip, Unroutable6)
78-
}
79-
80-
return false
70+
isPublic := false
71+
ma.ForEach(a, func(c ma.Component) bool {
72+
switch c.Protocol().Code {
73+
case ma.P_IP6ZONE:
74+
return true
75+
default:
76+
return false
77+
case ma.P_IP4:
78+
ip := net.IP(c.RawValue())
79+
isPublic = !inAddrRange(ip, Private4) && !inAddrRange(ip, Unroutable4)
80+
case ma.P_IP6:
81+
ip := net.IP(c.RawValue())
82+
isPublic = !inAddrRange(ip, Private6) && !inAddrRange(ip, Unroutable6)
83+
}
84+
return false
85+
})
86+
return isPublic
8187
}
8288

8389
// IsPrivateAddr returns true if the IP part of the mutiaddr is in a private network
8490
func IsPrivateAddr(a ma.Multiaddr) bool {
85-
ip, err := a.ValueForProtocol(ma.P_IP4)
86-
if err == nil {
87-
return inAddrRange(ip, Private4)
88-
}
89-
90-
ip, err = a.ValueForProtocol(ma.P_IP6)
91-
if err == nil {
92-
return inAddrRange(ip, Private6)
93-
}
94-
95-
return false
91+
isPrivate := false
92+
ma.ForEach(a, func(c ma.Component) bool {
93+
switch c.Protocol().Code {
94+
case ma.P_IP6ZONE:
95+
return true
96+
default:
97+
return false
98+
case ma.P_IP4:
99+
isPrivate = inAddrRange(net.IP(c.RawValue()), Private4)
100+
case ma.P_IP6:
101+
isPrivate = inAddrRange(net.IP(c.RawValue()), Private6)
102+
}
103+
return false
104+
})
105+
return isPrivate
96106
}
97107

98-
func inAddrRange(s string, ipnets []*net.IPNet) bool {
99-
ip := net.ParseIP(s)
108+
func inAddrRange(ip net.IP, ipnets []*net.IPNet) bool {
100109
for _, ipnet := range ipnets {
101110
if ipnet.Contains(ip) {
102111
return true

0 commit comments

Comments
 (0)