You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
kratos/internal/host/host.go

89 lines
1.8 KiB

4 years ago
package host
import (
"fmt"
4 years ago
"net"
"strconv"
)
// ExtractHostPort from address
func ExtractHostPort(addr string) (host string, port uint64, err error) {
var ports string
host, ports, err = net.SplitHostPort(addr)
if err != nil {
return
}
port, err = strconv.ParseUint(ports, 10, 16) //nolint:gomnd
return
}
func isValidIP(addr string) bool {
ip := net.ParseIP(addr)
4 years ago
return ip.IsGlobalUnicast() && !ip.IsInterfaceLocalMulticast()
4 years ago
}
// Port return a real port.
func Port(lis net.Listener) (int, bool) {
if addr, ok := lis.Addr().(*net.TCPAddr); ok {
return addr.Port, true
}
return 0, false
}
// Extract returns a private addr and port.
func Extract(hostPort string, lis net.Listener) (string, error) {
addr, port, err := net.SplitHostPort(hostPort)
if err != nil && lis == nil {
4 years ago
return "", err
}
if lis != nil {
p, ok := Port(lis)
if !ok {
return "", fmt.Errorf("failed to extract port: %v", lis.Addr())
4 years ago
}
port = strconv.Itoa(p)
4 years ago
}
if len(addr) > 0 && (addr != "0.0.0.0" && addr != "[::]" && addr != "::") {
return net.JoinHostPort(addr, port), nil
}
ifaces, err := net.Interfaces()
if err != nil {
return "", err
4 years ago
}
lowest := int(^uint(0) >> 1)
var result net.IP
4 years ago
for _, iface := range ifaces {
if (iface.Flags & net.FlagUp) == 0 {
continue
}
if iface.Index < lowest || result == nil {
lowest = iface.Index
}
if result != nil {
continue
}
4 years ago
addrs, err := iface.Addrs()
if err != nil {
continue
}
for _, rawAddr := range addrs {
var ip net.IP
switch addr := rawAddr.(type) {
case *net.IPAddr:
ip = addr.IP
case *net.IPNet:
ip = addr.IP
default:
continue
}
if isValidIP(ip.String()) {
result = ip
4 years ago
}
}
}
if result != nil {
return net.JoinHostPort(result.String(), port), nil
}
4 years ago
return "", nil
}