// HostPortToIP parses a host:port to a TCPAddr without resolving names.
// If given a context IP, it will resolve localhost to match the context's IP family.
771585
func HostPortToIP(hostport string, ctx *net.TCPAddr) (hostaddr *net.TCPAddr, err error) {
	host, port, err := net.SplitHostPort(hostport)
	if err != nil {
		return nil, err
	}
	iport, err := strconv.Atoi(port)
	if err != nil || iport < 0 || iport > 0xFFFF {
		return nil, fmt.Errorf("invalid port %d", iport)
	}
	var addr net.IP
	if ctx != nil && host == "localhost" {
		if ctx.IP.To4() != nil {
			addr = net.IPv4(127, 0, 0, 1)
		} else {
			addr = net.IP{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}
		}
	} else if addr = net.ParseIP(host); addr == nil {
		return nil, fmt.Errorf("could not parse IP %s", host)
	}

	return &net.TCPAddr{IP: addr, Port: iport}, nil
}
428470
func (hp *hostPort) networkHostPort() network.HostPort {
	return network.HostPort{
		Address: network.Address{
			Value:     hp.Value,
			Type:      network.AddressType(hp.AddressType),
			Scope:     network.Scope(hp.Scope),
			SpaceName: network.SpaceName(hp.SpaceName),
		},
		Port: hp.Port,
	}
}
617224
func HostPort(s, defaultPort string) (string, error) {
	addr, port, err := net.SplitHostPort(s)
	if port == "" {
		port = defaultPort
	}
	if err != nil {
		if net.ParseIP(s) == nil {
			return "", fmt.Errorf("must specify an IP address: `%s'", s)
		}
		return net.JoinHostPort(s, port), nil
	}

	if net.ParseIP(addr) == nil {
		return "", fmt.Errorf("must specify an IP address: `%s'", addr)
	}
	return net.JoinHostPort(addr, port), nil
}
146539
func (c *Container) Port(ctx context.Context, port string) (string, error) {
	if bindings, ok := c.container.NetworkSettings.Ports[nat.Port(port)]; ok {
		result := []string{}
		for _, binding := range bindings {
			result = append(result, binding.HostIP+":"+binding.HostPort)
		}

		return strings.Join(result, "\n"), nil
	}
	return "", nil
}
106224
func FindTabletByHostAndPort(tabletMap map[string]*topo.TabletInfo, addr, portName string, port int32) (*topodatapb.TabletAlias, error) {
	for _, ti := range tabletMap {
		if ti.Hostname == addr && ti.PortMap[portName] == port {
			return ti.Alias, nil
		}
	}
	return nil, topo.NewError(topo.NoNode, addr+":"+portName)
}
1337832
func leaderIP(leader string) (string, error) {
	// TODO(jdef) it's unclear why we drop the port here
	nameAddressPair := strings.Split(leader, "@")
	if len(nameAddressPair) != 2 {
		return "", errors.New("Invalid leader address: " + leader)
	}
	hostPort := nameAddressPair[1]
	host, _, err := net.SplitHostPort(hostPort)
	if err != nil {
		return "", err
	}
	return host, nil
}
814102
func IPAddrToSockaddr(addr *net.IPAddr) Sockaddr {
	return IPAndZoneToSockaddr(addr.IP, addr.Zone)
}
18518
func ResolveHostname(addr string) string {
	if idx := strings.IndexByte(addr, ':'); idx == 0 {
		// only port, then return the localhost hostname
		return "localhost"
	} else if idx > 0 {
		return addr[0:idx]
	}
	// it's already hostname
	return addr
}
1282366
func (r *ringDescriber) getHostInfo(ip net.IP, port int) (*HostInfo, error) {
	var host *HostInfo
	iter := r.session.control.withConnHost(func(ch *connHost) *Iter {
		if ch.host.ConnectAddress().Equal(ip) {
			host = ch.host
			return nil
		}

		return ch.conn.query(context.TODO(), "SELECT * FROM system.peers")
	})

	if iter != nil {
		rows, err := iter.SliceMap()
		if err != nil {
			return nil, err
		}

		for _, row := range rows {
			h, err := r.session.hostInfoFromMap(row, port)
			if err != nil {
				return nil, err
			}

			if h.ConnectAddress().Equal(ip) {
				host = h
				break
			}
		}

		if host == nil {
			return nil, errors.New("host not found in peers table")
		}
	}

	if host == nil {
		return nil, errors.New("unable to fetch host info: invalid control connection")
	} else if host.invalidConnectAddr() {
		return nil, fmt.Errorf("host ConnectAddress invalid ip=%v: %v", ip, host)
	}

	return host, nil
}
17459
func (m *Memberlist) resolveAddr(hostStr string) ([]ipPort, error) {
	// This captures the supplied port, or the default one.
	hostStr = ensurePort(hostStr, m.config.BindPort)
	host, sport, err := net.SplitHostPort(hostStr)
	if err != nil {
		return nil, err
	}
	lport, err := strconv.ParseUint(sport, 10, 16)
	if err != nil {
		return nil, err
	}
	port := uint16(lport)

	// If it looks like an IP address we are done. The SplitHostPort() above
	// will make sure the host part is in good shape for parsing, even for
	// IPv6 addresses.
	if ip := net.ParseIP(host); ip != nil {
		return []ipPort{ipPort{ip, port}}, nil
	}

	// First try TCP so we have the best chance for the largest list of
	// hosts to join. If this fails it's not fatal since this isn't a standard
	// way to query DNS, and we have a fallback below.
	ips, err := m.tcpLookupIP(host, port)
	if err != nil {
		m.logger.Printf("[DEBUG] memberlist: TCP-first lookup failed for '%s', falling back to UDP: %s", hostStr, err)
	}
	if len(ips) > 0 {
		return ips, nil
	}

	// If TCP didn't yield anything then use the normal Go resolver which
	// will try UDP, then might possibly try TCP again if the UDP response
	// indicates it was truncated.
	ans, err := net.LookupIP(host)
	if err != nil {
		return nil, err
	}
	ips = make([]ipPort, 0, len(ans))
	for _, ip := range ans {
		ips = append(ips, ipPort{ip, port})
	}
	return ips, nil
}
1134337
func (c *Config) SSHProxyHostPort() (string, int) {
	if c.SSHProxyAddr != "" {
		addr, err := utils.ParseAddr(c.SSHProxyAddr)
		if err == nil {
			return addr.Host(), addr.Port(defaults.SSHProxyListenPort)
		}
	}

	webProxyHost, _ := c.WebProxyHostPort()
	return webProxyHost, defaults.SSHProxyListenPort
}
540967
func keyToIPNet(key string) (parsedPrefix *net.IPNet, host bool, err error) {
	requiredPrefix := fmt.Sprintf("%s/", path.Join(IPIdentitiesPath, AddressSpace))
	if !strings.HasPrefix(key, requiredPrefix) {
		err = fmt.Errorf("Found invalid key %s outside of prefix %s", key, IPIdentitiesPath)
		return
	}

	suffix := strings.TrimPrefix(key, requiredPrefix)

	// Key is formatted as "prefix/192.0.2.0/24" for CIDRs
	_, parsedPrefix, err = net.ParseCIDR(suffix)
	if err != nil {
		// Key is likely a host in the format "prefix/192.0.2.3"
		parsedIP := net.ParseIP(suffix)
		if parsedIP == nil {
			err = fmt.Errorf("unable to parse IP from suffix %s", suffix)
			return
		}
		err = nil
		host = true
		ipv4 := parsedIP.To4()
		bits := net.IPv6len * 8
		if ipv4 != nil {
			parsedIP = ipv4
			bits = net.IPv4len * 8
		}
		parsedPrefix = &net.IPNet{IP: parsedIP, Mask: net.CIDRMask(bits, bits)}
	}

	return
}
115070
func ResolveIPv4Addrs(addr string) ([]string, error) {
	host, port, err := net.SplitHostPort(addr)
	if err != nil {
		return nil, err
	}
	ipAddrs, err := net.LookupIP(host)
	if err != nil {
		return nil, err
	}
	result := make([]string, 0, len(ipAddrs))
	for _, ipAddr := range ipAddrs {
		ipv4 := ipAddr.To4()
		if ipv4 != nil {
			result = append(result, net.JoinHostPort(ipv4.String(), port))
		}
	}
	if len(result) == 0 {
		return nil, fmt.Errorf("no IPv4addr for name %v", host)
	}
	return result, nil
}
1268206
func targetToAddr(target string) (*net.TCPAddr, error) {
	if strings.Contains(target, ":") {
		// addr host:port passed
		var err error
		addr, err := net.ResolveTCPAddr("tcp", target)
		if err != nil {
			return nil, fmt.Errorf("couldn't parse dst address: %v", err)
		}
		return addr, nil
	}
	// try to find port by pid then, connect to local
	pid, err := strconv.Atoi(target)
	if err != nil {
		return nil, fmt.Errorf("couldn't parse PID: %v", err)
	}
	port, err := internal.GetPort(pid)
	if err != nil {
		return nil, fmt.Errorf("couldn't get port for PID %v: %v", pid, err)
	}
	addr, _ := net.ResolveTCPAddr("tcp", "127.0.0.1:"+port)
	return addr, nil
}
734149
func (c *Cluster) HostWithInternalAddr(ipAddr net.IP) (*Host, bool) {
	if err := c.Update(); err != nil {
		c.logger.Log("level", "error", "message", "error getting the ip address using the internal cache", "stack", err)
		return nil, false
	}
	c.mu.Lock()
	defer c.mu.Unlock()

	if cached, exists := c.hostByInternalAddr[ipAddr.String()]; exists {
		return cached.get(), true
	} else {
		return nil, false
	}
}
461041
func parseHostContainerAddrs() (host net.Addr, container net.Addr) {
	var (
		proto         = flag.String("proto", "tcp", "proxy protocol")
		hostIP        = flag.String("host-ip", "", "host ip")
		hostPort      = flag.Int("host-port", -1, "host port")
		containerIP   = flag.String("container-ip", "", "container ip")
		containerPort = flag.Int("container-port", -1, "container port")
	)

	flag.Parse()

	switch *proto {
	case "tcp":
		host = &net.TCPAddr{IP: net.ParseIP(*hostIP), Port: *hostPort}
		container = &net.TCPAddr{IP: net.ParseIP(*containerIP), Port: *containerPort}
	case "udp":
		host = &net.UDPAddr{IP: net.ParseIP(*hostIP), Port: *hostPort}
		container = &net.UDPAddr{IP: net.ParseIP(*containerIP), Port: *containerPort}
	case "sctp":
		host = &sctp.SCTPAddr{IP: []net.IP{net.ParseIP(*hostIP)}, Port: *hostPort}
		container = &sctp.SCTPAddr{IP: []net.IP{net.ParseIP(*containerIP)}, Port: *containerPort}
	default:
		log.Fatalf("unsupported protocol %s", *proto)
	}

	return host, container
}
132949
func (f *SockaddrFuncs) GetInterfaceIP(namedIfRE string) (string, error) {
	return sockaddr.GetInterfaceIP(namedIfRE)
}