diff --git a/api/service/networkinfo/service.go b/api/service/networkinfo/service.go index 1e08a7b51..c460f9157 100644 --- a/api/service/networkinfo/service.go +++ b/api/service/networkinfo/service.go @@ -113,7 +113,7 @@ func (s *Service) Run() { // DoService does network info. func (s *Service) DoService() { - _, ipv4Net, err := net.ParseCIDR("100.64.0.0/10") + _, cgnPrefix, err := net.ParseCIDR("100.64.0.0/10") if err != nil { utils.GetLogInstance().Error("can't parse CIDR", "error", err) return @@ -137,7 +137,7 @@ func (s *Service) DoService() { continue } nip := netaddr.(*net.TCPAddr).IP - if nip.IsGlobalUnicast() || ipv4Net.Contains(nip) { + if (nip.IsGlobalUnicast() && !utils.IsPrivateIP(nip)) || cgnPrefix.Contains(nip) { ip = nip.String() port = fmt.Sprintf("%d", netaddr.(*net.TCPAddr).Port) break diff --git a/internal/utils/utils.go b/internal/utils/utils.go index 73fc96c71..6e847da13 100644 --- a/internal/utils/utils.go +++ b/internal/utils/utils.go @@ -8,6 +8,7 @@ import ( "io" "log" mrand "math/rand" + "net" "os" "regexp" "strconv" @@ -19,6 +20,7 @@ import ( ) var lock sync.Mutex +var privateNets []*net.IPNet // PrivKeyStore is used to persist private key to/from file type PrivKeyStore struct { @@ -27,6 +29,18 @@ type PrivKeyStore struct { func init() { bls.Init(bls.BLS12_381) + + for _, cidr := range []string{ + "127.0.0.0/8", // IPv4 loopback + "10.0.0.0/8", // RFC1918 + "172.16.0.0/12", // RFC1918 + "192.168.0.0/16", // RFC1918 + "::1/128", // IPv6 loopback + "fe80::/10", // IPv6 link-local + } { + _, block, _ := net.ParseCIDR(cidr) + privateNets = append(privateNets, block) + } } // Unmarshal is a function that unmarshals the data from the @@ -214,3 +228,13 @@ func LoadKeyFromFile(keyfile string) (key p2p_crypto.PrivKey, pk p2p_crypto.PubK key, pk, err = LoadPrivateKey(keyStruct.Key) return key, pk, err } + +// IsPrivateIP checks if an IP address is private or not +func IsPrivateIP(ip net.IP) bool { + for _, block := range privateNets { + if block.Contains(ip) { + return true + } + } + return false +} diff --git a/internal/utils/utils_test.go b/internal/utils/utils_test.go index f0027df6b..4c03d85d8 100644 --- a/internal/utils/utils_test.go +++ b/internal/utils/utils_test.go @@ -3,6 +3,7 @@ package utils import ( "bytes" "encoding/hex" + "net" "os" "testing" @@ -157,3 +158,38 @@ func TestSaveLoadKeyFile(t *testing.T) { os.Remove(filename) os.Remove(nonexist) } + +func TestIsPrivateIP(t *testing.T) { + addr := []struct { + ip net.IP + isPrivate bool + }{ + { + net.IPv4(127, 0, 0, 1), + true, + }, + { + net.IPv4(172, 31, 82, 23), + true, + }, + { + net.IPv4(192, 168, 82, 23), + true, + }, + { + net.IPv4(54, 172, 99, 189), + false, + }, + { + net.IPv4(10, 1, 0, 1), + true, + }, + } + + for _, a := range addr { + r := IsPrivateIP(a.ip) + if r != a.isPrivate { + t.Errorf("IP: %v, IsPrivate: %v, Expected: %v", a.ip, r, a.isPrivate) + } + } +}