...

Source file src/edge-infra.dev/pkg/lib/networkvalidator/networkvalidator.go

Documentation: edge-infra.dev/pkg/lib/networkvalidator

     1  package networkvalidator
     2  
     3  import (
     4  	"fmt"
     5  	"net"
     6  	"regexp"
     7  	"strings"
     8  )
     9  
    10  var (
    11  	domainRegex   = regexp.MustCompile(`^(?i)[a-z0-9-]+(\.[a-z0-9-]+)+\.?$`)
    12  	hostnameRegex = regexp.MustCompile(`^[-a-z0-9]+(\.[-a-z0-9]+)*$`)
    13  )
    14  
    15  const hostnameSpec string = "must be between 2 and 63 characters long and contain only lowercase alphanumeric characters, hyphens and periods"
    16  
    17  func ValidateIP(ip string) bool {
    18  	if ipVal := net.ParseIP(ip); ipVal == nil {
    19  		return false
    20  	}
    21  	return true
    22  }
    23  
    24  func ValidateMacAddress(macAddress string) (string, error) {
    25  	hardwareAddr, err := net.ParseMAC(macAddress)
    26  	return hardwareAddr.String(), err
    27  }
    28  
    29  func ValidateCIDR(address string, prefix int) bool {
    30  	cidr := fmt.Sprintf("%s/%d", address, prefix)
    31  	return IsValidCIDR(cidr)
    32  }
    33  
    34  func IsValidCIDR(subnet string) bool {
    35  	_, _, err := net.ParseCIDR(subnet)
    36  	return err == nil
    37  }
    38  
    39  func IsValidDomain(domain string) bool {
    40  	return domainRegex.MatchString(domain)
    41  }
    42  
    43  func IsValidHostname(hostname string) error {
    44  	if len(hostname) < 2 || len(hostname) > 64 {
    45  		return fmt.Errorf("invalid hostname length %v: must be between 2 and 63 characters long", len(hostname))
    46  	}
    47  
    48  	if strings.HasPrefix(hostname, ".") ||
    49  		strings.HasPrefix(hostname, "-") ||
    50  		strings.HasSuffix(hostname, ".") ||
    51  		strings.HasSuffix(hostname, "-") {
    52  		return fmt.Errorf("invalid hostname '%v': must not start or end with hyphens or periods", hostname)
    53  	}
    54  
    55  	if !hostnameRegex.MatchString(hostname) {
    56  		return fmt.Errorf("invalid hostname '%v': %v", hostname, hostnameSpec)
    57  	}
    58  
    59  	return nil
    60  }
    61  

View as plain text