-
Notifications
You must be signed in to change notification settings - Fork 14
/
mautil.go
52 lines (47 loc) · 1.17 KB
/
mautil.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Package mautil provider multiaddr utility functions.
package mautil
import (
"github.com/multiformats/go-multiaddr"
manet "github.com/multiformats/go-multiaddr/net"
)
// FilterPrivateIPs returns a new slice of multiaddrs with any private,
// loopback, or unspecified IP multiaddrs removed. If no multiaddrs are
// removed, then returns the original slice.
func FilterPrivateIPs(maddrs []multiaddr.Multiaddr) []multiaddr.Multiaddr {
var pvt []int
for i, maddr := range maddrs {
if maddr == nil {
continue
}
ip, err := manet.ToIP(maddr)
if err != nil {
continue
}
if ip.IsPrivate() || ip.IsLoopback() || ip.IsUnspecified() {
pvt = append(pvt, i)
}
}
// If no private addrs, return original slice.
if len(pvt) == 0 {
return maddrs
}
// If no non-private addrs, return nothing.
notPrivLen := len(maddrs) - len(pvt)
if notPrivLen == 0 {
return nil
}
// Return new slice with non-private addrs.
newAddrs := make([]multiaddr.Multiaddr, 0, notPrivLen)
skip := pvt[0]
for i, maddr := range maddrs {
if i == skip {
if len(pvt) > 1 {
pvt = pvt[1:]
skip = pvt[0]
}
continue
}
newAddrs = append(newAddrs, maddr)
}
return newAddrs
}