github.com/prebid/prebid-server/v2@v2.18.0/util/iputil/validator.go (about)

     1  package iputil
     2  
     3  import (
     4  	"net"
     5  )
     6  
     7  // IPValidator is the interface for validating an ip address and version.
     8  type IPValidator interface {
     9  	// IsValid returns true when an IP address is determined to be valid.
    10  	IsValid(net.IP, IPVersion) bool
    11  }
    12  
    13  // PublicNetworkIPValidator validates an ip address which is not contained in the list of known private networks.
    14  type PublicNetworkIPValidator struct {
    15  	IPv4PrivateNetworks []net.IPNet
    16  	IPv6PrivateNetworks []net.IPNet
    17  }
    18  
    19  // IsValid implements the IPValidator interface.
    20  func (v PublicNetworkIPValidator) IsValid(ip net.IP, ver IPVersion) bool {
    21  	var privateNetworks []net.IPNet
    22  	switch ver {
    23  	case IPv4:
    24  		privateNetworks = v.IPv4PrivateNetworks
    25  	case IPv6:
    26  		privateNetworks = v.IPv6PrivateNetworks
    27  	default:
    28  		return false
    29  	}
    30  
    31  	for _, ipNet := range privateNetworks {
    32  		if ipNet.Contains(ip) {
    33  			return false
    34  		}
    35  	}
    36  
    37  	return true
    38  }
    39  
    40  // VersionIPValidator validates an ip address based on the desired ip version.
    41  type VersionIPValidator struct {
    42  	Version IPVersion
    43  }
    44  
    45  // IsValid implements the IPValidator interface.
    46  func (v VersionIPValidator) IsValid(ip net.IP, ver IPVersion) bool {
    47  	return ver == v.Version
    48  }