github.com/telepresenceio/telepresence/v2@v2.20.0-pro.6.0.20240517030216-236ea954e789/pkg/iputil/parse.go (about) 1 package iputil 2 3 import ( 4 "fmt" 5 "math" 6 "net" 7 "strconv" 8 ) 9 10 // Parse is like net.ParseIP but converts an IPv4 in 16 byte form to its 4 byte form. 11 func Parse(ipStr string) (ip net.IP) { 12 if ip = net.ParseIP(ipStr); ip != nil { 13 if ip4 := ip.To4(); ip4 != nil { 14 ip = ip4 15 } 16 } 17 return 18 } 19 20 // SplitToIPPort splits the given address into an IP and a port number. It's 21 // an error if the address is based on a hostname rather than an IP. 22 func SplitToIPPort(netAddr net.Addr) (net.IP, uint16, error) { 23 addr := netAddr.String() 24 host, portStr, err := net.SplitHostPort(addr) 25 if err != nil { 26 return nil, 0, fmt.Errorf("address %q is not an IP and a port", addr) 27 } 28 ip := Parse(host) 29 p, err := strconv.ParseUint(portStr, 10, 16) 30 if err != nil || ip == nil { 31 return nil, 0, fmt.Errorf("address %q does not have an integer port <= to %d", addr, math.MaxUint16) 32 } 33 return ip, uint16(p), nil 34 }