Parse an internet address ``netloc`` and return a tuple with
``host`` and ``port``.
8418
def parse_address(netloc, default_port=8000):
    ''''''
    if isinstance(netloc, tuple):
        if len(netloc) != 2:
            raise ValueError('Invalid address %s' % str(netloc))
        return netloc
    #
    netloc = native_str(netloc)
    auth = None
    # Check if auth is available
    if '@' in netloc:
        auth, netloc = netloc.split('@')
    if netloc.startswith("unix:"):
        host = netloc.split("unix:")[1]
        return '%s@%s' % (auth, host) if auth else host
    # get host
    if '[' in netloc and ']' in netloc:
        host = netloc.split(']')[0][1:].lower()
    elif ':' in netloc:
        host = netloc.split(':')[0].lower()
    elif netloc == "":
        host = "0.0.0.0"
    else:
        host = netloc.lower()
    # get port
    netloc = netloc.split(']')[-1]
    if ":" in netloc:
        port = netloc.split(':', 1)[1]
        if not port.isdigit():
            raise ValueError("%r is not a valid port number." % port)
        port = int(port)
    else:
        port = default_port
    return ('%s@%s' % (auth, host) if auth else host, port)
581474
def split_hostname_from_port(cls, hostname):
        """"""
        bits = hostname.split(":", 2)
        p = None
        d = bits[0]
        if len(bits) == 2:
            p = int(bits[1])

        return d, p
461416
def parse_addr(addr, *, proto=None, host=None):
    
    port = None

    if isinstance(addr, Address):
        return addr
    elif isinstance(addr, str):
        if addr.startswith('http://'):
            proto, addr = 'http', addr[7:]
        if addr.startswith('udp://'):
            proto, addr = 'udp', addr[6:]
        elif addr.startswith('tcp://'):
            proto, addr = 'tcp', addr[6:]
        elif addr.startswith('unix://'):
            proto, addr = 'unix', addr[7:]
        a, _, b = addr.partition(':')
        host = a or host
        port = b or port
    elif isinstance(addr, (tuple, list)):
        # list is not good
        a, b = addr
        host = a or host
        port = b or port
    elif isinstance(addr, int):
        port = addr
    else:
        raise ValueError('bad value')

    if port is not None:
        port = int(port)
    return Address(proto, host, port)
759999
def makeMNBaseURL(url):
    """"""
    o = urllib.parse.urlparse(url, scheme=d1_common.const.DEFAULT_MN_PROTOCOL)
    if o.netloc and o.path:
        netloc = o.netloc
        path = o.path
    elif o.netloc:
        netloc = o.netloc
        path = d1_common.const.DEFAULT_MN_PATH
    elif o.path:
        s = o.path.split('/', 1)
        netloc = s[0]
        if len(s) == 1:
            path = d1_common.const.DEFAULT_MN_PATH
        else:
            path = s[1]
    else:
        netloc = d1_common.const.DEFAULT_MN_HOST
        path = d1_common.const.DEFAULT_MN_PATH
    return urllib.parse.urlunparse(
        (o.scheme, netloc, path, o.params, o.query, o.fragment)
    )
1353072
def get_host(url):
    
    p = parse_url(url)
    return p.scheme or 'http', p.hostname, p.port
1347828
def host_from_uri(uri):
    
    default_ports = {
        'HTTP': '80',
        'HTTPS': '443',
    }

    sch, netloc, path, par, query, fra = urlparse(uri)
    if ':' in netloc:
        netloc, port = netloc.split(':', 1)
    else:
        port = default_ports.get(sch.upper())

    return netloc, port
867502
def parse_source(info):
    

    if "extractor_key" in info:
        source = info["extractor_key"]
        lower_source = source.lower()

        for key in SOURCE_TO_NAME:
            lower_key = key.lower()
            if lower_source == lower_key:
                source = SOURCE_TO_NAME[lower_key]

        if source != "Generic":
            return source

    if "url" in info and info["url"] is not None:
        p = urlparse(info["url"])
        if p and p.netloc:
            return p.netloc

    return "Unknown"
785767
def parse_dbus_address(address):
    """"""
    if address == 'session':
        address = os.environ.get('DBUS_SESSION_BUS_ADDRESS')
        if not address:
            raise ValueError('$DBUS_SESSION_BUS_ADDRESS not set')
    elif address == 'system':
        address = os.environ.get('DBUS_SYSTEM_BUS_ADDRESS',
                                 'unix:path=/var/run/dbus/system_bus_socket')
    addresses = []
    for addr in address.split(';'):
        p1 = addr.find(':')
        if p1 == -1:
            raise ValueError('illegal address string: {}'.format(addr))
        kind = addr[:p1]
        args = dict((kv.split('=') for kv in addr[p1+1:].split(',')))
        if kind == 'unix':
            if 'path' in args:
                addr = args['path']
            elif 'abstract' in args:
                addr = '\0' + args['abstract']
            else:
                raise ValueError('require "path" or "abstract" for unix')
        elif kind == 'tcp':
            if 'host' not in args or 'port' not in args:
                raise ValueError('require "host" and "port" for tcp')
            addr = (args['host'], int(args['port']))
        else:
            raise ValueError('unknown transport: {}'.format(kind))
        addresses.append(addr)
    return addresses
858188
def parse_resolv(src='/etc/resolv.conf'):
    '''
    
    '''

    nameservers = []
    ip4_nameservers = []
    ip6_nameservers = []
    search = []
    sortlist = []
    domain = ''
    options = []

    try:
        with salt.utils.files.fopen(src) as src_file:
            # pylint: disable=too-many-nested-blocks
            for line in src_file:
                line = salt.utils.stringutils.to_unicode(line).strip().split()

                try:
                    (directive, arg) = (line[0].lower(), line[1:])
                    # Drop everything after # or ; (comments)
                    arg = list(itertools.takewhile(lambda x: x[0] not in ('#', ';'), arg))
                    if directive == 'nameserver':
                        addr = arg[0]
                        try:
                            ip_addr = ipaddress.ip_address(addr)
                            version = ip_addr.version
                            ip_addr = str(ip_addr)
                            if ip_addr not in nameservers:
                                nameservers.append(ip_addr)
                            if version == 4 and ip_addr not in ip4_nameservers:
                                ip4_nameservers.append(ip_addr)
                            elif version == 6 and ip_addr not in ip6_nameservers:
                                ip6_nameservers.append(ip_addr)
                        except ValueError as exc:
                            log.error('%s: %s', src, exc)
                    elif directive == 'domain':
                        domain = arg[0]
                    elif directive == 'search':
                        search = arg
                    elif directive == 'sortlist':
                        # A sortlist is specified by IP address netmask pairs.
                        # The netmask is optional and defaults to the natural
                        # netmask of the net. The IP address and optional
                        # network pairs are separated by slashes.
                        for ip_raw in arg:
                            try:
                                ip_net = ipaddress.ip_network(ip_raw)
                            except ValueError as exc:
                                log.error('%s: %s', src, exc)
                            else:
                                if '/' not in ip_raw:
                                    # No netmask has been provided, guess
                                    # the "natural" one
                                    if ip_net.version == 4:
                                        ip_addr = six.text_type(ip_net.network_address)
                                        # pylint: disable=protected-access
                                        mask = salt.utils.network.natural_ipv4_netmask(ip_addr)
                                        ip_net = ipaddress.ip_network(
                                            '{0}{1}'.format(ip_addr, mask),
                                            strict=False
                                        )
                                    if ip_net.version == 6:
                                        # TODO
                                        pass

                                if ip_net not in sortlist:
                                    sortlist.append(ip_net)
                    elif directive == 'options':
                        # Options allows certain internal resolver variables to
                        # be modified.
                        if arg[0] not in options:
                            options.append(arg[0])
                except IndexError:
                    continue

        if domain and search:
            # The domain and search keywords are mutually exclusive.  If more
            # than one instance of these keywords is present, the last instance
            # will override.
            log.debug(
                '%s: The domain and search keywords are mutually exclusive.',
                src
            )

        return {
            'nameservers':     nameservers,
            'ip4_nameservers': ip4_nameservers,
            'ip6_nameservers': ip6_nameservers,
            'sortlist':        [ip.with_netmask for ip in sortlist],
            'domain':          domain,
            'search':          search,
            'options':         options
        }
    except IOError:
        return {}
559786
def ParseMultiple(self, result_dicts):
    """"""
    for result_dict in result_dicts:
      args = {"ifname": result_dict["Description"]}
      args["mac_address"] = binascii.unhexlify(
          result_dict["MACAddress"].replace(":", ""))

      self._ConvertIPs([("IPAddress", "addresses"),
                        ("DefaultIPGateway", "ip_gateway_list"),
                        ("DHCPServer", "dhcp_server_list")], result_dict, args)

      if "DHCPLeaseExpires" in result_dict:
        args["dhcp_lease_expires"] = self.WMITimeStrToRDFDatetime(
            result_dict["DHCPLeaseExpires"])

      if "DHCPLeaseObtained" in result_dict:
        args["dhcp_lease_obtained"] = self.WMITimeStrToRDFDatetime(
            result_dict["DHCPLeaseObtained"])

      yield rdf_client_network.Interface(**args)

      yield rdf_client_network.DNSClientConfiguration(
          dns_server=result_dict["DNSServerSearchOrder"],
          dns_suffix=result_dict["DNSDomainSuffixSearchOrder"])
612945
def url_to_host_port(url, port=None):
    
    if not url.startswith('http://') and not url.startswith('https://'):
        url = 'http://' + url

    if not port:
        port = RPC_SERVER_PORT

    urlinfo = urllib2.urlparse.urlparse(url)
    hostport = urlinfo.netloc

    parts = hostport.split('@')
    if len(parts) > 2:
        return None, None

    if len(parts) == 2:
        hostport = parts[1]

    parts = hostport.split(':')
    if len(parts) > 2:
        return None, None

    if len(parts) == 2:
        try:
            port = int(parts[1])
            assert 0 < port and port < 65535, 'Invalid port'
        except TypeError:
            return None, None

    return parts[0], port
800353
def modLocationPort(self, location):
        
        components = urlparse.urlparse(location)
        reverse_proxy_port = self.father.getHost().port
        reverse_proxy_host = self.father.getHost().host
        # returns an ordered dict of urlparse.ParseResult components
        _components = components._asdict()
        _components['netloc'] = '%s:%d' % (
            reverse_proxy_host, reverse_proxy_port
        )
        return urlparse.urlunparse(_components.values())
597085
def _parse_ip(addr):
    

    # Parse the IP address
    try:
        address = netaddr.IPAddress(addr.strip())
    except (ValueError, netaddr.AddrFormatError):
        return None

    # Canonicalize it, if possible
    if address.version == 6:
        try:
            return address.ipv4()
        except netaddr.AddrConversionError:
            pass

    return address
459355
def splithost(url):
    """"""
    global _hostprog
    if _hostprog is None:
        import re
        _hostprog = re.compile('^//([^/?]*)(.*)$')

    match = _hostprog.match(url)
    if match:
        host_port = match.group(1)
        path = match.group(2)
        if path and not path.startswith('/'):
            path = '/' + path
        return host_port, path
    return None, url
513132
def parse_netloc(scheme, netloc):
    """"""
    auth, _netloc = netloc.split('@')
    sender, token = auth.split(':')
    if ':' in _netloc:
        domain, port = _netloc.split(':')
        port = int(port)
    else:
        domain = _netloc
        if scheme == 'https':
            port = 443
        else:
            port = 80
    return dict(sender=sender, token=token, domain=domain, port=port)
786832
def _parse_addr(self, addr): 
        '''  '''
        ipv = 0
        try:
            socket.inet_pton(socket.AF_INET6, addr)
            # Convert ::FFFF:x.y.z.y to IPv4
            if addr.lower().startswith('::ffff:'):
                try:
                    socket.inet_pton(socket.AF_INET, addr)
                    ipv = 4
                except:
                    ipv = 6
            else:
                ipv = 6
        except:
            socket.inet_pton(socket.AF_INET, addr)
            ipv = 4
        return ipv
287571
def parse_address(address):
		

		if len(address) == 0:
			return None

		try:
			return WIPV4Address(address)
		except ValueError:
			pass

		try:
			return WFQDN(address)
		except ValueError:
			pass

		raise ValueError('Unable to parse address string. It must be an IP address or FQDN')