Converts IPv4 address to binary form.
356458
def _get_binary_from_ipv4(self, ip_addr):
        """"""

        return struct.unpack("!L", socket.inet_pton(socket.AF_INET,
                                                    ip_addr))[0]
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;
	}
348608
def ip2hex(ip):
    '''
    
    '''
    parts = ip.split(".")
    if len(parts) != 4: return None
    ipv = 0
    for part in parts:
        try:
            p = int(part)
            if p < 0 or p > 255: return None
            ipv = (ipv << 8) + p
        except:
            return None
    return ipv
866155
def _ipv4_text_to_int(self, ip_text):
        """"""
        if ip_text is None:
            return None
        assert isinstance(ip_text, str)
        return struct.unpack('!I', addrconv.ipv4.text_to_bin(ip_text))[0]
973541
def random_ipv4(cidr='10.0.0.0/8'):
    
    try:
        u_cidr = unicode(cidr)
    except NameError:
        u_cidr = cidr
    network = ipaddress.ip_network(u_cidr)
    start = int(network.network_address) + 1
    end = int(network.broadcast_address)
    randint = random.randrange(start, end)
    return ipaddress.ip_address(randint)
1033185
def ipv4_reassembly(frame):
    """"""
    if 'IPv4' in frame:
        ipv4 = frame['IPv4'].info
        if ipv4.flags.df:       # dismiss not fragmented frame
            return False, None
        data = dict(
            bufid=(
                ipv4.src,                                   # source IP address
                ipv4.dst,                                   # destination IP address
                ipv4.id,                                    # identification
                ipv4.proto.name,                            # payload protocol type
            ),
            num=frame.info.number,                          # original packet range number
            fo=ipv4.frag_offset,                            # fragment offset
            ihl=ipv4.hdr_len,                               # internet header length
            mf=ipv4.flags.mf,                               # more fragment flag
            tl=ipv4.len,                                    # total length, header includes
            header=bytearray(ipv4.packet.header),           # raw bytearray type header
            payload=bytearray(ipv4.packet.payload or b''),  # raw bytearray type payload
        )
        return True, data
    return False, None
888743
private int toInt(InetAddress inetAddress) {
        byte[] address = inetAddress.getAddress();
        int result = 0;
        for (int i = 0; i < address.length; i++) {
            result <<= 8;
            result |= address[i] & BYTE_MASK;
        }
        return result;
    }
1281857
private static long bytesToLong(byte[] address) {
        long ipnum = 0;
        for (int i = 0; i < 4; ++i) {
            long y = address[i];
            if (y < 0) {
                y += 256;
            }
            ipnum += y << ((3 - i) * 8);
        }
        return ipnum;
    }
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
398259
private function _toIp($binary)
    {
        $ip  = array();
        $tmp = explode(".", chunk_split($binary, 8, "."));
        for ($i = 0; $i < 4 ; $i++) {
            $ip[$i] = bindec($tmp[$i]);
        }

        return $ip;
    }
845007
def netmask(mask):
    '''
    
    '''
    if not isinstance(mask, string_types):
        return False

    octets = mask.split('.')
    if not len(octets) == 4:
        return False

    return ipv4_addr(mask) and octets == sorted(octets, reverse=True)
993353
def cidr_to_ipv4_netmask(cidr_bits):
    '''
    
    '''
    try:
        cidr_bits = int(cidr_bits)
        if not 1 <= cidr_bits <= 32:
            return ''
    except ValueError:
        return ''

    netmask = ''
    for idx in range(4):
        if idx:
            netmask += '.'
        if cidr_bits >= 8:
            netmask += '255'
            cidr_bits -= 8
        else:
            netmask += '{0:d}'.format(256 - (2 ** (8 - cidr_bits)))
            cidr_bits = 0
    return netmask
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));
    }
1310288
static byte[] validIpV4ToBytes(String ip) {
        int i;
        return new byte[] {
                ipv4WordToByte(ip, 0, i = ip.indexOf('.', 1)),
                ipv4WordToByte(ip, i + 1, i = ip.indexOf('.', i + 2)),
                ipv4WordToByte(ip, i + 1, i = ip.indexOf('.', i + 2)),
                ipv4WordToByte(ip, i + 1, ip.length())
        };
    }
1189645
public long convertIPBytes(byte[] ipBytes) {
        if (ipBytes.length == 4) {
            long ipLong = (((long)ipBytes[0]) << 24);
            ipLong |= (((long)ipBytes[1]) << 16);
            ipLong |= (((long)ipBytes[2]) << 8);
            ipLong |= (long)ipBytes[3];
            return ipLong;
        }
        return -1;
    }
596667
public static int ipv4ToInt( final Inet4Address    addr )
    {
        int    value = 0;

        for( byte    chunk : addr.getAddress() )
        {
            value <<= 8;
            value |= chunk & 0xff;
        }

        return value;
    }
560739
def set_ipv4(self, ip):
        
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        bin_ip = socket.inet_aton(ip)
        ifreq = struct.pack('16sH2s4s8s', self.name, socket.AF_INET, '\x00'*2, bin_ip, '\x00'*8)
        fcntl.ioctl(sock, self.SIOCSIFADDR, ifreq)
        ifreq = struct.pack('16sH', self.name, self.IFF_UP|self.IFF_POINTOPOINT|self.IFF_RUNNING|self.IFF_MULTICAST)
        fcntl.ioctl(sock, self.SIOCSIFFLAGS, ifreq)