Convert a hex string to an ip, if a failure occurs the original hex is
    returned. If 'invert=True' assume that ip from /proc/net/<proto>
172269
def hex2ip(hex_ip, invert=False):
    '''
    
    '''
    if len(hex_ip) == 32:  # ipv6
        ip = []
        for i in range(0, 32, 8):
            ip_part = hex_ip[i:i + 8]
            ip_part = [ip_part[x:x + 2] for x in range(0, 8, 2)]
            if invert:
                ip.append("{0[3]}{0[2]}:{0[1]}{0[0]}".format(ip_part))
            else:
                ip.append("{0[0]}{0[1]}:{0[2]}{0[3]}".format(ip_part))
        try:
            address = ipaddress.IPv6Address(":".join(ip))
            if address.ipv4_mapped:
                return str(address.ipv4_mapped)
            else:
                return address.compressed
        except ipaddress.AddressValueError as ex:
            log.error('hex2ip - ipv6 address error: %s', ex)
            return hex_ip

    try:
        hip = int(hex_ip, 16)
    except ValueError:
        return hex_ip
    if invert:
        return '{3}.{2}.{1}.{0}'.format(hip >> 24 & 255,
                                        hip >> 16 & 255,
                                        hip >> 8 & 255,
                                        hip & 255)
    return '{0}.{1}.{2}.{3}'.format(hip >> 24 & 255,
                                    hip >> 16 & 255,
                                    hip >> 8 & 255,
                                    hip & 255)
197234
def _explode_shorthand_ip_string(self):
        
        if isinstance(self, _BaseNet):
            ip_str = str(self.ip)
        else:
            ip_str = str(self)

        ip_int = self._ip_int_from_string(ip_str)
        parts = []
        for i in xrange(self._HEXTET_COUNT):
            parts.append('%04x' % (ip_int & 0xFFFF))
            ip_int >>= 16
        parts.reverse()
        if isinstance(self, _BaseNet):
            return '%s/%d' % (':'.join(parts), self.prefixlen)
        return ':'.join(parts)
901833
def is_ip(string):
    
    mo = re.match(r'(\d+)\.(\d+)\.(\d+)\.(\d+)', string)
    if mo is None:
        return False
    for group in mo.groups():
        if int(group) not in list(range(0, 256)):
            return False
    return True
47854
public static Inet4Address forIPv4String(String ipString) {
        requireNonNull(ipString);

        try{
            InetAddress parsed = forString(ipString);

            if (parsed instanceof Inet4Address)
                return (Inet4Address) parsed;

        } catch(Exception ignored){}

        throw new IllegalArgumentException(format("Invalid IPv4 representation: %s", ipString));
    }
803618
private static boolean checkIpv4(byte[] bytes, int pos, int length) {
		int start = pos;
		for (int i = pos; i < length; i++) {
			// assume at least one more symbol is present after dot
			if (i == length - 1 && bytes[i] == '.') {
				return false;
			}
			if (bytes[i] == '.' || i == length - 1) {
				int v;
				if (i - start == 0 && i != length - 1) {
					return false;
				}
				try {
					v = trimAndDecodePositiveInt(bytes, start, i - start);
				} catch (ParseException e) {
					return false;
				}
				if (v < 0 || v > 255) return false;
				start = i + 1;
			}
		}
		return true;
	}
574449
def bin_to_text(ip):
    
    if len(ip) == 4:
        return ipv4_to_str(ip)
    elif len(ip) == 16:
        return ipv6_to_str(ip)
    else:
        raise struct.error('Invalid ip address length: %s' % len(ip))
870081
def lookup_reverse(ip_address):
    """"""
    try:
        type(ipaddress.ip_address(ip_address))
    except ValueError:
        return {}

    record = reversename.from_address(ip_address)
    hostname = str(resolver.query(record, "PTR")[0])[:-1]
    return {'hostname': hostname}
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)
920729
def to_hex_string(data):
    '''  '''
    if isinstance(data, int):
        return '%02X' % data
    return ':'.join([('%02X' % o) for o in data])
1305817
def next_ip(arg)
      octets = arg.split(/\./, 4).map(&:to_i)
      octets[3] += 1
      raise "out of ips!" if octets[3] > 255
      return octets.map(&:to_s).join(".")
    end
389892
def is_valid_ip(ip: str) -> bool:
    
    if not ip or "\x00" in ip:
        # getaddrinfo resolves empty strings to localhost, and truncates
        # on zero bytes.
        return False
    try:
        res = socket.getaddrinfo(
            ip, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST
        )
        return bool(res)
    except socket.gaierror as e:
        if e.args[0] == socket.EAI_NONAME:
            return False
        raise
    return True
324564
def str_to_inet(address):
    
    # First try ipv4 and then ipv6
    try:
        return socket.inet_pton(socket.AF_INET, address)
    except socket.error:
        return socket.inet_pton(socket.AF_INET6, address)
845726
def convert_to_ip(self):
        """"""
        self._values, self._header._unit = self._header.data_type.to_ip(
                self._values, self._header.unit)
1274312
protected String convertToHex(int i) {

        String hexString = Integer.toHexString(i);
        while (hexString.length() < 2) {
            hexString = "0" + hexString;
        }
        return hexString;
    }
620078
public static int ipv4StringToInt(String ipv4Str) {
		byte[] byteAddress = ip4StringToBytes(ipv4Str);
		if (byteAddress == null) {
			return 0;
		} else {
			return NumberUtil.toInt(byteAddress);
		}
	}
713136
def valid_ipv4(ip):
    
    match =  _valid_ipv4.match(ip)
    if match is None:
        return False

    octets  = match.groups()
    if len(octets) != 4:
        return False

    first = int(octets[0])
    if first < 1 or first > 254:
        return False

    for i in range(1, 4):
        octet = int(octets[i])
        if octet < 0 or octet > 255:
            return False

    return True
416195
def i2osp(x, x_len):
    '''
    '''
    if x > 256**x_len:
        raise exceptions.IntegerTooLarge
    h = hex(x)[2:]
    if h[-1] == 'L':
        h = h[:-1]
    if len(h) & 1 == 1:
        h = '0%s' % h
    x = binascii.unhexlify(h)
    return b'\x00' * int(x_len-len(x)) + x