Convert an IPv6 address in Compact Representation Notation 
    (RFC 1924) to printable representation ;-)
    Returns None on error.
324077
def in6_ctop(addr):
    
    #if len(addr) != 20 or not reduce(lambda x,y: x and y, map(lambda x: x in _rfc1924map, addr)):
    if len(addr) != 20 or not all(map(lambda x: x in _rfc1924map, addr)):
        return None
    i = 0
    for c in addr:
        j = _rfc1924map.index(c)
        i = 85*i + j
    res = []
    for j in range(4):
        res.append(struct.pack("!I", i%2**32))
        i = i//(2**32)
    res.reverse()
    return inet_ntop(socket.AF_INET6, b"".join(res))
1048261
function normalizeIP(addr) {
  var claimsToBeIPv6 = /:/.test(addr);
  if(claimsToBeIPv6) {
    var ip6 = new Address6(addr);
    if(ip6.valid) {
      return ip6.canonicalForm();
    } else if(ip6.error) {
      throw new Error(ip6.error);
    } else {
      throw new Error("Unknown error while parsing IPv6 address.");
    }
  } else {
    var isIPv4 = false;
    try {
      var ip4 = new Address4(addr);
      isIPv4 = ip4.valid;
    }
    //  Any exception thrown implies not a valid IPv4 address.
    catch(error) {
      throw new Error("Unknown error while parsing IPv4 Address: "+error);
    }

    if(isIPv4) {
      return addr;
    }
    else {
      throw new Error("Unknown error while parsing IPv4 Address.");
    }
  }
}
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
475858
def addr(self,address):
        ''''''
        if isinstance(address,basestring):
            # If you just gave me a single string, assume its "XXXX XXXX"
            addr = address.split()
        else:
            addr = list(address)
        # Convert to actual hex if you give me strings
        for i in xrange(len(addr)):
            if isinstance(addr[i],basestring):
                addr[i] = int(addr[i],16)
        for frame in self.raw_frames:
            if frame['addr']==address:
                return frame
810000
public String toBase85String() {
		//first we see if we obtained this address from a base 85 string
		//in the case of a prefix, applying the prefix changes the value
		IPAddressString originator = getAddressfromString();
		if(originator != null && (!isPrefixed() || getNetworkPrefixLength() == IPv6Address.BIT_COUNT) && originator.isBase85IPv6()) {
			return originator.toString();
		}
		String result;
		if(hasNoStringCache() || (result = stringCache.base85String) == null) {
			if(hasZone()) {
				stringCache.base85String = result = getSection().toBase85String(getZone());
			} else {
				result = getSection().toBase85String();//the cache is shared so no need to update it here
			}
		}
		return result;
	}
1035937
def address(addr):
    

    if ':' in addr:
        # Using rpartition here means we should be able to support
        # IPv6, but only with a strict syntax
        host, _sep, port = addr.rpartition(':')

        # Convert the port to a number
        try:
            port = int(port)
        except ValueError:
            raise ValueError("invalid port number %r" % port)

        addr = (host, port)

    return addr
1058332
def inet_pton(af, addr):
    """"""
    print('hello')
    if af == socket.AF_INET:
        return inet_aton(addr)
    elif af == socket.AF_INET6:
        # IPv6: The use of "::" indicates one or more groups of 16 bits of zeros.
        # We deal with this form of wildcard using a special marker. 
        JOKER = b"*"
        while b"::" in addr:
            addr = addr.replace(b"::", b":" + JOKER + b":")
        joker_pos = None 
        
        # The last part of an IPv6 address can be an IPv4 address
        ipv4_addr = None
        if b"." in addr:
            ipv4_addr = addr.split(b":")[-1]
           
        result = b""
        parts = addr.split(b":")
        for part in parts:
            if part == JOKER:
                # Wildcard is only allowed once
                if joker_pos is None:
                   joker_pos = len(result)
                else:
                   raise Exception("Illegal syntax for IP address")
            elif part == ipv4_addr: # FIXME: Make sure IPv4 can only be last part
                # FIXME: inet_aton allows IPv4 addresses with less than 4 octets 
                result += socket.inet_aton(ipv4_addr)
            else:
                # Each part must be 16bit. Add missing zeroes before decoding. 
                try:
                    result += part.rjust(4, b"0").decode("hex")
                except TypeError:
                    raise Exception("Illegal syntax for IP address")
                    
        # If there's a wildcard, fill up with zeros to reach 128bit (16 bytes) 
        if JOKER in addr:
            result = (result[:joker_pos] + b"\x00" * (16 - len(result))
                      + result[joker_pos:])
    
        if len(result) != 16:
            raise Exception("Illegal syntax for IP address")
        return result 
    else:
        raise Exception("Address family not supported")
450751
def anonymize(remote_addr):
    
    if not isinstance(remote_addr, text_type) and isinstance(remote_addr, str):
        remote_addr = remote_addr.decode('ascii', 'ignore')
    try:
        ipv4 = ipaddress.IPv4Address(remote_addr)
        return u''.join(ipv4.exploded.rsplit('.', 1)[0]) + '.' + '0'
    except ipaddress.AddressValueError:
        try:
            ipv6 = ipaddress.IPv6Address(remote_addr)
            if ipv6.ipv4_mapped is not None:
                return anonymize(text_type(ipv6.ipv4_mapped))
            return u'' + ipv6.exploded.rsplit(':', 5)[0] + ':' + ':'.join(['0000'] * 5)
        except ipaddress.AddressValueError:
            return u'0.0.0.0'
365968
public static String toAddressString(InetSocketAddress address) {
        if (address == null) {
            return StringUtils.EMPTY;
        } else {
            return toIpString(address) + ":" + address.getPort();
        }
    }
486519
def ipv4_to_str(ip):
    
    if isinstance(ip, numbers.Integral):
        return addrconv.ipv4.bin_to_text(struct.pack("!I", ip))
    else:
        return addrconv.ipv4.bin_to_text(ip)
1266126
def inet_ntoa(address):
    

    if len(address) != 16:
        raise ValueError("IPv6 addresses are 16 bytes long")
    hex = address.encode('hex_codec')
    chunks = []
    i = 0
    l = len(hex)
    while i < l:
        chunk = hex[i : i + 4]
        # strip leading zeros.  we do this with an re instead of
        # with lstrip() because lstrip() didn't support chars until
        # python 2.2.2
        m = _leading_zero.match(chunk)
        if not m is None:
            chunk = m.group(1)
        chunks.append(chunk)
        i += 4
    #
    # Compress the longest subsequence of 0-value chunks to ::
    #
    best_start = 0
    best_len = 0
    start = -1
    last_was_zero = False
    for i in xrange(8):
        if chunks[i] != '0':
            if last_was_zero:
                end = i
                current_len = end - start
                if current_len > best_len:
                    best_start = start
                    best_len = current_len
                last_was_zero = False
        elif not last_was_zero:
            start = i
            last_was_zero = True
    if last_was_zero:
        end = 8
        current_len = end - start
        if current_len > best_len:
            best_start = start
            best_len = current_len
    if best_len > 0:
        if best_start == 0 and \
           (best_len == 6 or
            best_len == 5 and chunks[5] == 'ffff'):
            # We have an embedded IPv4 address
            if best_len == 6:
                prefix = '::'
            else:
                prefix = '::ffff:'
            hex = prefix + dns.ipv4.inet_ntoa(address[12:])
        else:
            hex = ':'.join(chunks[:best_start]) + '::' + \
                  ':'.join(chunks[best_start + best_len:])
    else:
        hex = ':'.join(chunks)
    return hex
88036
def to_ipv6(key):
    """"""

    if key[-2:] != '.k':
        raise ValueError('Key does not end with .k')

    key_bytes = base32.decode(key[:-2])
    hash_one = sha512(key_bytes).digest()
    hash_two = sha512(hash_one).hexdigest()

    return ':'.join([hash_two[i:i+4] for i in range(0, 32, 4)])
542779
def to_raw_address(addr, section):
        """"""
        return addr - section.header.VirtualAddress + section.header.PointerToRawData
909573
private static CharSequence convertReverseDNSIPv6(String str, int suffixStartIndex) throws AddressStringException {
		StringBuilder builder = new StringBuilder(suffixStartIndex);
		StringBuilder low = new StringBuilder();
		StringBuilder high = new StringBuilder();
		int segCount = 0;
		for(int i = suffixStartIndex - 1; i >= 0; ) {
			boolean isRange = false;
			for(int j = 0; j < 4; j++) {
				char c1 = str.charAt(i--);
				if(i >= 0) {
					char c2 = str.charAt(i--);
					if(c2 == IPv4Address.SEGMENT_SEPARATOR) {
						if(c1 == IPAddress.SEGMENT_WILDCARD) {
							isRange = true;
							low.append('0');
							high.append('f');
						} else {
							if(isRange) {
								throw new AddressStringException(str, i + 1);
							}
							low.append(c1);
							high.append(c1);
						}
					} else if(c2 == IPAddress.RANGE_SEPARATOR) {
						high.append(c1);
						if(i >= 1) {
							c2 = str.charAt(i--);
							low.append(c2);
							boolean isFullRange = (c2 == '0' && c1 == 'f');
							if(isRange && !isFullRange) {
								throw new AddressStringException(str, i + 1);
							}
							c2 = str.charAt(i--);
							if(c2 != IPv4Address.SEGMENT_SEPARATOR) {
								throw new AddressStringException(str, i + 1);
							}
						} else {
							throw new AddressStringException(str, i);
						}
						isRange = true;
					} else {
						throw new AddressStringException(str, i + 1);
					}
				} else if(j < 3) {
					throw new AddressStringException(str, i + 1);
				} else {
					if(c1 == IPAddress.SEGMENT_WILDCARD) {
						isRange = true;
						low.append('0');
						high.append('f');
					} else {
						if(isRange) {
							throw new AddressStringException(str, 0);
						}
						low.append(c1);
						high.append(c1);
					}
				}
			}
			segCount++;
			if(builder.length() > 0) {
				builder.append(IPv6Address.SEGMENT_SEPARATOR);
			}
			builder.append(low);
			if(isRange) {
				builder.append(IPAddress.RANGE_SEPARATOR).append(high);
			}
			low.setLength(0);
			high.setLength(0);
		}
		if(segCount != IPv6Address.SEGMENT_COUNT) {
			throw new AddressStringException(str, 0);
		}
		return builder;
	}
1297095
def inet_to_str(inet):
    
    # First try ipv4 and then ipv6
    try:
        return socket.inet_ntop(socket.AF_INET, inet)
    except ValueError:
        return socket.inet_ntop(socket.AF_INET6, inet)
1340875
def _get_ipv6_from_binary(self, bin_addr):
        """"""

        hi = bin_addr >> 64
        lo = bin_addr & 0xFFFFFFFF
        return socket.inet_ntop(socket.AF_INET6, struct.pack("!QQ", hi, lo))
1084229
def from_string(address):
		
		address = address.split('.')
		if len(address) != WIPV4Address.octet_count:
			raise ValueError('Invalid ip address: %s' % address)

		result = WIPV4Address()
		for i in range(WIPV4Address.octet_count):
			result.__address[i] = WBinArray(int(address[i]), WFixedSizeByteArray.byte_size)
		return result