badguardhome/internal/aghnet/ipdetector.go
Eugene Burkov 3a67cc2c45 Pull request: create aghnet package
Merge in DNS/adguard-home from mk-aghnet to master

Updates #2829.

Squashed commit of the following:

commit 519806c04b8d0517aacce9c31f2d06ab56631937
Merge: 92376c86 97361234
Author: Eugene Burkov <e.burkov@adguard.com>
Date:   Tue Mar 16 19:13:56 2021 +0300

    Merge branch 'master' into mk-aghnet

commit 92376c8665e529191aa482432f9d5e3e2e3afdc8
Author: Eugene Burkov <e.burkov@adguard.com>
Date:   Tue Mar 16 18:37:22 2021 +0300

    aghnet: fix linux

commit 7f36d19b0e650d4e4fc5cf9ea4b501a7f636abeb
Author: Eugene Burkov <e.burkov@adguard.com>
Date:   Tue Mar 16 18:08:30 2021 +0300

    aghnet: mv network utils from util

commit aa68c70c1146b8c32303c6e037953a41aa7d72f9
Author: Eugene Burkov <e.burkov@adguard.com>
Date:   Tue Mar 16 17:30:06 2021 +0300

    aghnet: mv ipDetector here

commit b033657f5c5ee91f869c36508a5eb15976a174a0
Author: Eugene Burkov <e.burkov@adguard.com>
Date:   Tue Mar 16 17:24:07 2021 +0300

    all: mk aghnet package, rename sysutil package
2021-03-16 19:42:15 +03:00

74 lines
1.4 KiB
Go

package aghnet
import "net"
// IPDetector describes IP address properties.
type IPDetector struct {
nets []*net.IPNet
}
// NewIPDetector returns a new IP detector.
func NewIPDetector() (ipd *IPDetector, err error) {
specialNetworks := []string{
"0.0.0.0/8",
"10.0.0.0/8",
"100.64.0.0/10",
"127.0.0.0/8",
"169.254.0.0/16",
"172.16.0.0/12",
"192.0.0.0/24",
"192.0.0.0/29",
"192.0.2.0/24",
"192.88.99.0/24",
"192.168.0.0/16",
"198.18.0.0/15",
"198.51.100.0/24",
"203.0.113.0/24",
"240.0.0.0/4",
"255.255.255.255/32",
"::1/128",
"::/128",
"64:ff9b::/96",
// Since this network is used for mapping IPv4 addresses, we
// don't include it.
// "::ffff:0:0/96",
"100::/64",
"2001::/23",
"2001::/32",
"2001:2::/48",
"2001:db8::/32",
"2001:10::/28",
"2002::/16",
"fc00::/7",
"fe80::/10",
}
ipd = &IPDetector{
nets: make([]*net.IPNet, len(specialNetworks)),
}
for i, ipnetStr := range specialNetworks {
var ipnet *net.IPNet
_, ipnet, err = net.ParseCIDR(ipnetStr)
if err != nil {
return nil, err
}
ipd.nets[i] = ipnet
}
return ipd, nil
}
// DetectSpecialNetwork returns true if IP address is contained by any of
// special-purpose IP address registries according to RFC-6890
// (https://tools.ietf.org/html/rfc6890).
func (ipd *IPDetector) DetectSpecialNetwork(ip net.IP) bool {
for _, ipnet := range ipd.nets {
if ipnet.Contains(ip) {
return true
}
}
return false
}