Interprets an address in standard tuple format to determine if it
    is valid, and, if so, which socket family it is.  Returns the
    socket family.
978031
def addr_info(addr):
    

    # If it's a string, it's in the UNIX family
    if isinstance(addr, basestring):
        return socket.AF_UNIX

    # Verify that addr is a tuple
    if not isinstance(addr, collections.Sequence):
        raise ValueError("address is not a tuple")

    # Make sure it has at least 2 fields
    if len(addr) < 2:
        raise ValueError("cannot understand address")

    # Sanity-check the port number
    if not (0 <= addr[1] < 65536):
        raise ValueError("cannot understand port number")

    # OK, first field should be an IP address; suck it out...
    ipaddr = addr[0]

    # Empty string means IPv4
    if not ipaddr:
        if len(addr) != 2:
            raise ValueError("cannot understand address")

        return socket.AF_INET

    # See if it's valid...
    if netaddr.valid_ipv6(ipaddr):
        if len(addr) > 4:
            raise ValueError("cannot understand address")

        return socket.AF_INET6
    elif netaddr.valid_ipv4(ipaddr):
        if len(addr) != 2:
            raise ValueError("cannot understand address")

        return socket.AF_INET

    raise ValueError("cannot understand address")
808114
def _isbtaddr(address):
    
    # Define validity regex. Accept either ":" or "-" as separators.
    global _validbtaddr
    if _validbtaddr is None:
        import re
        _validbtaddr = re.compile("((\d|[a-f]){2}(:|-)){5}(\d|[a-f]){2}",
                re.IGNORECASE)
    import types
    if not isinstance(address, str):
        return False
    return _validbtaddr.match(address) is not None
742726
def _inet6_ntop(addr):
    
    # IPv6 addresses have 128bits (16 bytes)
    if len(addr) != 16:
        raise ValueError("invalid length of packed IP address string")

    # Decode to hex representation
    address = ":".join(plain_str(bytes_hex(addr[idx:idx + 2])).lstrip('0') or '0'  # noqa: E501
                       for idx in range(0, 16, 2))

    try:
        # Get the longest set of zero blocks. We need to take a look
        # at group 1 regarding the length, as 0:0:1:0:0:2:3:4 would
        # have two matches: 0:0: and :0:0: where the latter is longer,
        # though the first one should be taken. Group 1 is in both
        # cases 0:0.
        match = max(_IP6_ZEROS.finditer(address),
                    key=lambda m: m.end(1) - m.start(1))
        return '{}::{}'.format(address[:match.start()], address[match.end():])
    except ValueError:
        return address
993560
def parse_group_address(addr):
    

    if addr is None:
        raise KNXException("No address given")

    res = None

    if re.match('[0-9]+$', addr):
        res = int(addr)

    match = re.match("([0-9]+)/([0-9]+)$", addr)
    if match:
        main = match.group(1)
        sub = match.group(2)
        res = int(main) * 2048 + int(sub)

    match = re.match("([0-9]+)/([0-9]+)/([0-9]+)$", addr)
    if match:
        main = match.group(1)
        middle = match.group(2)
        sub = match.group(3)
        res = int(main) * 256 * 8 + int(middle) * 256 + int(sub)

    if res is None:
        raise KNXException("Address {} does not match any address scheme".
                           format(addr))

    return res
54224
def _get_address_family(table):
        
        address_family_mapping = {
            'inet': 'ipv4',
            'inet6': 'ipv6',
            'inetflow': 'flow'
        }
        family = table.split('.')[-2]
        try:
            address_family = address_family_mapping[family]
        except KeyError:
            address_family = family
        return address_family
1116480
def valid_address(address):
    
    if not address:
        return False

    components = str(address).split(':')
    if len(components) > 2 or not valid_hostname(components[0]):
        return False

    if len(components) == 2 and not valid_port(components[1]):
        return False

    return True
746295
def _inet6_pton(addr):
    
    joker_pos = None
    result = b""
    addr = plain_str(addr)
    if addr == '::':
        return b'\x00' * 16
    if addr.startswith('::'):
        addr = addr[1:]
    if addr.endswith('::'):
        addr = addr[:-1]
    parts = addr.split(":")
    nparts = len(parts)
    for i, part in enumerate(parts):
        if not part:
            # "::" indicates one or more groups of 2 null bytes
            if joker_pos is None:
                joker_pos = len(result)
            else:
                # Wildcard is only allowed once
                raise _INET6_PTON_EXC
        elif i + 1 == nparts and '.' in part:
            # The last part of an IPv6 address can be an IPv4 address
            if part.count('.') != 3:
                # we have to do this since socket.inet_aton('1.2') ==
                # b'\x01\x00\x00\x02'
                raise _INET6_PTON_EXC
            try:
                result += socket.inet_aton(part)
            except socket.error:
                raise _INET6_PTON_EXC
        else:
            # Each part must be 16bit. Add missing zeroes before decoding.
            try:
                result += hex_bytes(part.rjust(4, "0"))
            except (binascii.Error, TypeError):
                raise _INET6_PTON_EXC
    # If there's a wildcard, fill up with zeros to reach 128bit (16 bytes)
    if joker_pos is not None:
        if len(result) == 16:
            raise _INET6_PTON_EXC
        result = (result[:joker_pos] + b"\x00" * (16 - len(result)) +
                  result[joker_pos:])
    if len(result) != 16:
        raise _INET6_PTON_EXC
    return result
601253
def select_address_family(host, port):
    """"""
    # disabled due to problems with current ipv6 implementations
    # and various operating systems.  Probably this code also is
    # not supposed to work, but I can't come up with any other
    # ways to implement this.
    # try:
    #     info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
    #                               socket.SOCK_STREAM, 0,
    #                               socket.AI_PASSIVE)
    #     if info:
    #         return info[0][0]
    # except socket.gaierror:
    #     pass
    if host.startswith("unix://"):
        return socket.AF_UNIX
    elif ":" in host and hasattr(socket, "AF_INET6"):
        return socket.AF_INET6
    return socket.AF_INET
932442
def btc_is_p2sh_address( address ):
    
    vb = keylib.b58check.b58check_version_byte( address )
    if vb == multisig_version_byte:
        return True
    else:
        return False
52285
def inet_pton(address_family, ip_string):
    
    global __inet_pton
    if __inet_pton is None:
        if hasattr(socket, 'inet_pton'):
            __inet_pton = socket.inet_pton
        else:
            from ospd import win_socket
            __inet_pton = win_socket.inet_pton

    return __inet_pton(address_family, ip_string)
796849
public boolean isIPv4CompatibleAddress() {
        if ((ipaddress[0] == 0x00) && (ipaddress[1] == 0x00) &&
            (ipaddress[2] == 0x00) && (ipaddress[3] == 0x00) &&
            (ipaddress[4] == 0x00) && (ipaddress[5] == 0x00) &&
            (ipaddress[6] == 0x00) && (ipaddress[7] == 0x00) &&
            (ipaddress[8] == 0x00) && (ipaddress[9] == 0x00) &&
            (ipaddress[10] == 0x00) && (ipaddress[11] == 0x00))  {
            return true;
        }
        return false;
    }
185865
public boolean isValidInet6Address(String inet6Address) {
        boolean containsCompressedZeroes = inet6Address.contains("::");
        if (containsCompressedZeroes && (inet6Address.indexOf("::") != inet6Address.lastIndexOf("::"))) {
            return false;
        }
        if ((inet6Address.startsWith(":") && !inet6Address.startsWith("::"))
                || (inet6Address.endsWith(":") && !inet6Address.endsWith("::"))) {
            return false;
        }
        String[] octets = inet6Address.split(":");
        if (containsCompressedZeroes) {
            List<String> octetList = new ArrayList<>(Arrays.asList(octets));
            if (inet6Address.endsWith("::")) {
                // String.split() drops ending empty segments
                octetList.add("");
            } else if (inet6Address.startsWith("::") && !octetList.isEmpty()) {
                octetList.remove(0);
            }
            octets = octetList.toArray(new String[0]);
        }
        if (octets.length > IPV6_MAX_HEX_GROUPS) {
            return false;
        }
        int validOctets = 0;
        int emptyOctets = 0; // consecutive empty chunks
        for (int index = 0; index < octets.length; index++) {
            String octet = octets[index];
            if (octet.length() == 0) {
                emptyOctets++;
                if (emptyOctets > 1) {
                    return false;
                }
            } else {
                emptyOctets = 0;
                // Is last chunk an IPv4 address?
                if (index == octets.length - 1 && octet.contains(".")) {
                    if (!isValidInet4Address(octet)) {
                        return false;
                    }
                    validOctets += 2;
                    continue;
                }
                if (octet.length() > IPV6_MAX_HEX_DIGITS_PER_GROUP) {
                    return false;
                }
                int octetInt = 0;
                try {
                    octetInt = Integer.parseInt(octet, BASE_16);
                } catch (NumberFormatException e) {
                    return false;
                }
                if (octetInt < 0 || octetInt > MAX_UNSIGNED_SHORT) {
                    return false;
                }
            }
            validOctets++;
        }
        if (validOctets > IPV6_MAX_HEX_GROUPS || (validOctets < IPV6_MAX_HEX_GROUPS && !containsCompressedZeroes)) {
            return false;
        }
        return true;
    }
103863
def get_addr(iface='lo0', iface_type='link'):
    
    if platform.system() in ['Darwin', 'Linux']:
        if iface_type == 'link':
            _AF_FAMILY = psutil.AF_LINK
        elif iface_type in ['inet', 'inet6']:
            _AF_FAMILY = getattr(socket, 'AF_{}'.format(iface_type.upper()))
        else:
            raise SystemError('Not valid address FAMILY')
    else:
        raise SystemExit('Unsupported System. Only Mac/Linux Supported')

    addrs = psutil.net_if_addrs()
    for n in addrs[iface]:
        if n.family == _AF_FAMILY:
            return n.address
1370542
def translate(self, addr):
        
        # get family of this address so we translate to the same
        family = socket.getaddrinfo(addr, 0, socket.AF_UNSPEC, socket.SOCK_STREAM)[0][0]
        host = socket.getfqdn(addr)
        for a in socket.getaddrinfo(host, 0, family, socket.SOCK_STREAM):
            try:
                return a[4][0]
            except Exception:
                pass
        return addr
292683
def _FormatSocketInet128Token(self, token_data):
    
    protocol = bsmtoken.BSM_PROTOCOLS.get(token_data.socket_family, 'UNKNOWN')
    ip_address = self._FormatPackedIPv6Address(token_data.ip_addresss)
    return {
        'protocols': protocol,
        'family': token_data.socket_family,
        'port': token_data.port_number,
        'address': ip_address}
880691
private boolean isTypeValid(char type) {
		return (type == MAPPED_ADDRESS || type == RESPONSE_ADDRESS
				|| type == SOURCE_ADDRESS || type == CHANGED_ADDRESS
				|| type == REFLECTED_FROM || type == XOR_MAPPED_ADDRESS
				|| type == ALTERNATE_SERVER || type == XOR_PEER_ADDRESS
				|| type == XOR_RELAYED_ADDRESS || type == DESTINATION_ADDRESS);
	}
988981
def address(self, s):
        
        s = parseable_str(s)
        return self.p2pkh(s) or self.p2sh(s) or self.p2pkh_segwit(s) or self.p2sh_segwit(s)