Parse provided hostname and extract port number

        :param host: Server hostname
        :type host: string
        :param port: Server port
        :return: Tuple of (host, port)
        :rtype: tuple
487758
def _parse_host(cls, host='localhost', port=0):
        
        if not port and (host.find(':') == host.rfind(':')):
            i = host.rfind(':')
            if i >= 0:
                host, port = host[:i], host[i + 1:]
                try:
                    port = int(port)
                except ValueError:
                    raise OSError('nonnumeric port')
        return host, port
513583
public static Hosts parse(String hostString, Integer explicitGlobalPort, Integer defaultPort) {
		List<String> hosts = new ArrayList<>();
		List<Integer> ports = new ArrayList<>();
		if ( hostString == null || hostString.trim().isEmpty() ) {
			return Hosts.NO_HOST;
		}
		// for each element between commas
		String[] splits = hostString.split( "," );
		for ( String rawSplit : splits ) {
			// remove whitespaces
			String split = rawSplit.trim();
			//
			Matcher matcher = HOST_AND_PORT_PATTERN.matcher( split );
			if ( matcher.matches() ) {
				setCleanHost( matcher, hosts );
				setPort( ports, matcher, explicitGlobalPort, splits, defaultPort );
			}
			else {
				throw LOG.unableToParseHost( hostString );
			}
		}
		return new Hosts( hosts, ports );
	}
666280
def extract_domain(host):
    
    host = re.sub('https?://', '', host)
    host = re.match('([^/]+)', host).groups()[0]
    domain = '.'.join(host.split('.')[-2:])
    if domain in _domains:
        domain = '.'.join(host.split('.')[-3:])
    return domain
1239762
def get_ips(host, port):
    
    ips = set()

    for af_type in (socket.AF_INET, socket.AF_INET6):
        try:
            records = socket.getaddrinfo(host, port, af_type, socket.SOCK_STREAM)
            ips.update(rec[4][0] for rec in records)
        except socket.gaierror as ex:
            pass

    return ips
350391
def host_and_port(host_or_port):
    
    if ':' in host_or_port:
        if len(host_or_port) == 1:
            return 'localhost:4200'
        elif host_or_port.startswith(':'):
            return 'localhost' + host_or_port
        return host_or_port
    return host_or_port + ':4200'
1008744
def _get_hosts_from_names(self, names):
        
        result = set()
        hosts = map(lambda x: x.strip(), names.split(','))
        for h in hosts:
            if valid_hostname(h.split(':')[0]):
                result.add(h if ':' in h else '%s:%d' % (h, self.PORT))
            else:
                raise conferr('Invalid hostname: %s' % h.split(':')[0])
        return list(result)
834979
def get_host(url):
    
    # This code is actually similar to urlparse.urlsplit, but much
    # simplified for our needs.
    port = None
    scheme = 'http'
    if '//' in url:
        scheme, url = url.split('://', 1)
    if '/' in url:
        url, _path = url.split('/', 1)
    if ':' in url:
        url, port = url.split(':', 1)
        port = int(port)
    return scheme, url, port
1221167
def valid_host_with_port(hostport):
    
    host, port = hostport.rsplit(":", 1) if ":" in hostport else (hostport, None)

    # first, validate host or IP
    if not valid_ipv4(host) and not valid_host(host):
        return False

    # now, validate port
    if port is not None and not valid_port(port):
        return False

    return True
281110
def hostname_with_port(self):
        ''''''
        default_port = RELATIVE_SCHEME_DEFAULT_PORTS.get(self.scheme)
        if not default_port:
            return ''

        assert '[' not in self.hostname
        assert ']' not in self.hostname

        if self.is_ipv6():
            hostname = '[{}]'.format(self.hostname)
        else:
            hostname = self.hostname

        if default_port != self.port:
            return '{}:{}'.format(hostname, self.port)
        else:
            return hostname
1289032
def _get_host(self, hostname):
        
        if hostname not in self.hosts:
            self.hosts[hostname] = {
                'groups': set(),
                'hostvars': {}
            }
        return self.hosts[hostname]
258643
def connect(self, host, port):
        
        if not port and (host.find(':') == host.rfind(':')):
            i = host.rfind(':')
            if i >= 0:
                host, port = host[:i], host[i+1:]
            try: port = int(port)
            except ValueError:
                raise socket.error, "nonnumeric port"
        #if self.verbose > 0:
        #    print 'connect:', (host, port)
        msg = "getaddrinfo returns an empty list"
        self.sock = None
        for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
            af, socktype, proto, canonname, sa = res
            try:
                self.sock = socket.socket(af, socktype, proto)
                #if self.debuglevel > 0: print 'connect:', (host, port)
                self.sock.connect(sa)
            except socket.error, msg:
                #if self.debuglevel > 0: print 'connect fail:', (host, port)
                self.close()
                continue
            break
        if not self.sock:
            raise socket.error, msg
735776
public static HostAndPort parseString(String from){
    // NOTE: redis answers with
    // '99aa9999aa9a99aa099aaa990aa99a09aa9a9999 9a09:9a9:a090:9a::99a slave 8c88888888cc08088cc8c8c888c88c8888c88cc8 0 1468251272993 37 connected'
    // for CLUSTER NODES, ASK and MOVED scenarios. That's why there is no possibility to parse address in 'correct' way.
    // Redis should switch to 'bracketized' (RFC 3986) IPv6 address.
    try {
      String[] parts = extractParts(from);
      String host = parts[0];
      int port = Integer.parseInt(parts[1]);
      return new HostAndPort(convertHost(host), port);
    } catch (NumberFormatException ex) {
      throw new IllegalArgumentException(ex);
    }
  }
1214379
def _build_connstr(host, port, bucket):
    
    hostlist = []
    if isinstance(host, (tuple, list)):
        for curhost in host:
            if isinstance(curhost, (list, tuple)):
                hostlist.append(_fmthost(*curhost))
            else:
                hostlist.append(curhost)
    else:
        hostlist.append(_fmthost(host, port))

    return 'http://{0}/{1}'.format(','.join(hostlist), bucket)
532543
def parse_hosts(hostsfile='/etc/hosts', hosts=None):
    '''
    
    '''
    if not hosts:
        try:
            with salt.utils.files.fopen(hostsfile, 'r') as fp_:
                hosts = salt.utils.stringutils.to_unicode(fp_.read())
        except Exception:
            return 'Error: hosts data was not found'

    hostsdict = {}
    for line in hosts.splitlines():
        if not line:
            continue
        if line.startswith('#'):
            continue
        comps = line.split()
        ip = comps[0]
        aliases = comps[1:]
        hostsdict.setdefault(ip, []).extend(aliases)

    return hostsdict
600981
def parse_host(parser, event, node):
    
    #pylint: disable=unused-argument

    host = ''

    (next_event, next_node) = six.next(parser)

    if next_event == pulldom.CHARACTERS:

        host = next_node.nodeValue

        (next_event, next_node) = six.next(parser)

    if not _is_end(next_event, next_node, 'HOST'):
        raise ParseError('Expecting end HOST')

    return host
1332977
def _expand_host(self, host):
        
        if isinstance(host, basestring):
            return (host, self.default_port)
        return tuple(host)
528638
def _build_base_url(self, host, port):
        
        parsed = urlparse(host)
        if not parsed.scheme:
            parsed = parsed._replace(scheme="http")
            parsed = parsed._replace(path="")
            netloc, parts = host, host.partition(":")
            if parts[1] == "" and port is not None:
                netloc = "{}:{}".format(parts[0], port)
            parsed = parsed._replace(netloc=netloc)
        parsed = parsed._replace(path=parsed.path.rstrip("/"))
        return parsed.geturl()