Convert a string representing an IPv4 address to 4 bytes.
491552
def ip_to_array(ipaddress):
    """"""
    res = []
    for i in ipaddress.split("."):
        res.append(int(i))

    assert len(res) == 4
    return res
87978
def sanitize_network(network, ip_version):
    

    import ipaddress

    if typepy.is_null_string(network) or network.lower() == "anywhere":
        return get_anywhere_network(ip_version)

    try:
        if ip_version == 4:
            ipaddress.IPv4Address(network)
            return network + "/32"

        if ip_version == 6:
            return ipaddress.IPv6Address(network).compressed
    except ipaddress.AddressValueError:
        pass

    # validate network str ---

    if ip_version == 4:
        return ipaddress.IPv4Network(six.text_type(network)).compressed

    if ip_version == 6:
        return ipaddress.IPv6Network(six.text_type(network)).compressed

    raise ValueError("unexpected ip version: {}".format(ip_version))
408713
private static boolean decodeIpv4Suffix(
      String input, int pos, int limit, byte[] address, int addressOffset) {
    int b = addressOffset;

    for (int i = pos; i < limit; ) {
      if (b == address.length) return false; // Too many groups.

      // Read a delimiter.
      if (b != addressOffset) {
        if (input.charAt(i) != '.') return false; // Wrong delimiter.
        i++;
      }

      // Read 1 or more decimal digits for a value in 0..255.
      int value = 0;
      int groupOffset = i;
      for (; i < limit; i++) {
        char c = input.charAt(i);
        if (c < '0' || c > '9') break;
        if (value == 0 && groupOffset != i) return false; // Reject unnecessary leading '0's.
        value = (value * 10) + c - '0';
        if (value > 255) return false; // Value out of range.
      }
      int groupLength = i - groupOffset;
      if (groupLength == 0) return false; // No digits.

      // We've successfully read a byte.
      address[b++] = (byte) value;
    }

    if (b != addressOffset + 4) return false; // Too few groups. We wanted exactly four.
    return true; // Success.
  }
17547
def get_text_v4(address, stream, mapped=False):
    

    if address == 0:
        return ""

    if mapped:
        size, _ = TWO_UINT64_uf(stream, address + 8)
        text_bytes = stream[address + 24: address + size]
    else:
        stream.seek(address + 8)
        size, _ = TWO_UINT64_u(stream.read(16))
        text_bytes = stream.read(size - 24)
    try:
        text = text_bytes.strip(b" \r\t\n\0").decode("utf-8")
    except UnicodeDecodeError as err:
        try:
            from cchardet import detect

            encoding = detect(text_bytes)["encoding"]
            text = text_bytes.decode(encoding).strip(" \r\t\n\0")
        except ImportError:
            logger.warning(
                'Unicode exception occured and "cChardet" package is '
                'not installed. Mdf version 4 expects "utf-8" '
                "strings and this package may detect if a different"
                " encoding was used"
            )
            raise err

    return text
1199414
public static String ipV4Address() {
        StringBuffer sb = new StringBuffer();
        sb.append(JDefaultNumber.randomIntBetweenTwoNumbers(2, 254) + "");
        sb.append(".");
        sb.append(JDefaultNumber.randomIntBetweenTwoNumbers(2, 254) + "");
        sb.append(".");
        sb.append(JDefaultNumber.randomIntBetweenTwoNumbers(2, 254) + "");
        sb.append(".");
        sb.append(JDefaultNumber.randomIntBetweenTwoNumbers(2, 254) + "");

        return sb.toString();

    }
989794
def from_bytes(VarInt, byte_string):
        '''
        
        '''
        num = byte_string
        if num[0] <= 0xfc:
            num = num[0:1]
            non_compact = False
        elif num[0] == 0xfd:
            num = num[1:3]
            non_compact = (num[-1:] == b'\x00')
        elif num[0] == 0xfe:
            num = num[1:5]
            non_compact = (num[-2:] == b'\x00\x00')
        elif num[0] == 0xff:
            num = num[1:9]
            non_compact = (num[-4:] == b'\x00\x00\x00\x00')
        if len(num) not in [1, 2, 4, 8]:
            raise ValueError('Malformed VarInt. Got: {}'
                             .format(byte_string.hex()))

        if (non_compact
            and ('overwinter' in riemann.get_current_network_name()
                 or 'sapling' in riemann.get_current_network_name())):
            raise ValueError('VarInt must be compact. Got: {}'
                             .format(byte_string.hex()))

        ret = VarInt(
            utils.le2i(num),
            length=len(num) + 1 if non_compact else 0)

        return ret
695558
def _get_afi(self, ip):
        

        parts = unicode(ip).split("/")
        if len(parts) == 1:
            # just an address
            if self._is_ipv4(ip):
                return 4
            elif self._is_ipv6(ip):
                return 6
            else:
                return None
        elif len(parts) == 2:
            # a prefix!
            try:
                pl = int(parts[1])
            except ValueError:
                # if casting parts[1] to int failes, this is not a prefix..
                return None

            if self._is_ipv4(parts[0]):
                if pl >= 0 and pl <= 32:
                    # prefix mask must be between 0 and 32
                    return 4
                # otherwise error
                return None
            elif self._is_ipv6(parts[0]):
                if pl >= 0 and pl <= 128:
                    # prefix mask must be between 0 and 128
                    return 6
                # otherwise error
                return None
            else:
                return None
        else:
            # more than two parts.. this is neither an address or a prefix
            return None
271630
public static function reverseIpv4(string $ip): string
    {
        $octets = array_reverse(explode('.', $ip));

        return implode('.', $octets).'.in-addr.arpa.';
    }
39027
public static Inet4Address fromIpv4String(String address) {
		byte[] bytes = ip4StringToBytes(address);
		if (bytes == null) {
			return null;
		} else {
			try {
				return (Inet4Address) Inet4Address.getByAddress(bytes);
			} catch (UnknownHostException e) {
				throw new AssertionError(e);
			}
		}
	}
947205
def target_to_ipv4_cidr(target):
    

    splitted = target.split('/')
    if len(splitted) != 2:
        return None
    try:
        start_packed = inet_pton(socket.AF_INET, splitted[0])
        block = int(splitted[1])
    except (socket.error, ValueError):
        return None
    if block <= 0 or block > 30:
        return None
    start_value = int(binascii.hexlify(start_packed), 16) >> (32 - block)
    start_value = (start_value << (32 - block)) + 1
    end_value = (start_value | (0xffffffff >> block)) - 1
    start_packed = struct.pack('!I', start_value)
    end_packed = struct.pack('!I', end_value)
    return ipv4_range_to_list(start_packed, end_packed)
1352151
def ipaddr(value, options=None):
    '''
    
    '''
    ipv4_obj = ipv4(value, options=options)
    ipv6_obj = ipv6(value, options=options)
    if ipv4_obj is None or ipv6_obj is None:
        # an IP address can be either IPv4 either IPv6
        # therefofe if the value passed as arg is not a list, at least one of the calls above will return None
        # if one of them is none, means that we should return only one of them
        return ipv4_obj or ipv6_obj  # one of them
    else:
        return ipv4_obj + ipv6_obj
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
259267
public static byte[]
    toByteArray(String s, int family) {
        if (family == IPv4)
            return parseV4(s);
        else if (family == IPv6)
            return parseV6(s);
        else
            throw new IllegalArgumentException("unknown address family");
    }
781981
def _get_ipv4_from_binary(self, bin_addr):
        """"""

        return socket.inet_ntop(socket.AF_INET, struct.pack("!L", bin_addr))
769521
def get_ipv4(hostname):
    
    addrinfo = socket.getaddrinfo(hostname, None, socket.AF_INET,
                                  socket.SOCK_STREAM)
    return [addrinfo[x][4][0] for x in range(len(addrinfo))]
1320154
def from_string(address):
		
		str_address = None

		if WMACAddress.re_dash_format.match(address):
			str_address = "".join(address.split("-"))
		elif WMACAddress.re_colon_format.match(address):
			str_address = "".join(address.split(":"))
		elif WMACAddress.re_cisco_format.match(address):
			str_address = "".join(address.split("."))
		elif WMACAddress.re_spaceless_format.match(address):
			str_address = address

		if str_address is None:
			raise ValueError("Invalid MAC address format: " + address)

		result = WMACAddress()
		for octet_index in range(WMACAddress.octet_count):
			octet = str_address[:2]
			result.__address[octet_index] = int(octet, 16)
			str_address = str_address[2:]

		return result
1179626
def compile_ip_v4(rule):
    
    if isinstance(rule.value, ipranges.Range):
        return rule
    return IPV4Rule(ipranges.from_str_v4(rule.value))