Converts IPv4 CIDR to subnet mask format

@param $cidr
@return string
180942
static public function ConvertIPv4CIDRToMask($cidr)
    {
        $subnetMask = str_pad("", $cidr, "1");

        $subnetMask = str_pad($subnetMask, 32, "0");

        $subnetMask = array_map(
            function($x) {
                return bindec($x);
            },
            str_split($subnetMask, 8)
        );

        return implode(".", $subnetMask);

    }
271630
public static function reverseIpv4(string $ip): string
    {
        $octets = array_reverse(explode('.', $ip));

        return implode('.', $octets).'.in-addr.arpa.';
    }
790898
protected static function cidrMatch32bit($ipAddr, $cidr)
    {
        list ($subNet, $bits) = explode('/', $cidr);
        $ipLong = \ip2long($ipAddr);
        $subnetLong = \ip2long($subNet);
        $mask = -1 << (32 - $bits);
        $subnetLong &= $mask; // nb: in case the supplied subnet wasn't correctly aligned
        return ($ipLong & $mask) == $subnetLong;
    }
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
1328029
protected function ipv4For($country)
    {
        $country = self::toUpper($country);

        if (!isset(self::$ipv4Ranges[$country])) {
            return '';
        }

        return static::randomElement(self::$ipv4Ranges[$country]) . mt_rand(1, 254);
    }
157050
public function anonymize($address) {
        $packedAddress = inet_pton($address);

        if (strlen($packedAddress) == 4) {
            return $this->anonymizeIPv4($address);
        } elseif (strlen($packedAddress) == 16) {
            return $this->anonymizeIPv6($address);
        } else {
            return "";
        }
    }
643673
public function generateV4() : string
    {
        return sprintf(
            '%04x%04x%04x%04x%04x%04x%04x%04x',
            // 32 bits for "time_low"
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            // 16 bits for "time_mid"
            mt_rand(0, 0xffff),
            // 16 bits for "time_hi_and_version",
            // four most significant bits holds version number 4
            mt_rand(0, 0x0fff) | 0x4000,
            // 16 bits, 8 bits for "clk_seq_hi_res",
            // 8 bits for "clk_seq_low",
            // two most significant bits holds zero and one for variant DCE1.1
            mt_rand(0, 0x3fff) | 0x8000,
            // 48 bits for "node"
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff),
            mt_rand(0, 0xffff)
        );
    }
531056
public static function cidr_to_range($cidr) {
		ref\cast::string($cidr, true);

		$range = array('min'=>0, 'max'=>0);
		$cidr = \array_pad(\explode('/', $cidr), 2, 0);
		ref\cast::int($cidr[1], true);

		// IPv4?
		if (\filter_var($cidr[0], \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4)) {
			// IPv4 is only 32-bit.
			ref\sanitize::to_range($cidr[1], 0, 32);

			if (0 === $cidr[1]) {
				$range['min'] = $range['max'] = sanitize::ip($cidr[0]);
			}
			else {
				// Work from binary.
				$cidr[1] = \bindec(\str_pad(\str_repeat('1', $cidr[1]), 32, '0'));

				// Calculate the range.
				$ip = \ip2long($cidr[0]);
				$netmask = $cidr[1];
				$first = ($ip & $netmask);
				$bc = $first | ~$netmask;

				$range['min'] = \long2ip($first);
				$range['max'] = \long2ip($bc);
			}
			return $range;
		}

		// IPv6? Of course a little more complicated.
		if (\filter_var($cidr[0], \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) {
			// IPv6 is only 128-bit.
			ref\sanitize::to_range($cidr[1], 0, 128);

			if (0 === $cidr[1]) {
				$range['min'] = $range['max'] = sanitize::ip($cidr[0]);
				return $range;
			}

			// Work from binary.
			$bin = \str_pad(\str_repeat('1', $cidr[1]), 128, '0');
			if (\function_exists('gmp_init')) {
				$cidr[1] = \gmp_strval(\gmp_init($bin, 2), 10);
			}
			else {
				$cidr[1] = bc::bindec($bin);
			}

			// Calculate the range.
			$ip = static::ip_to_number($cidr[0]);
			$netmask = $cidr[1];

			if (\function_exists('gmp_and')) {
				$first = \gmp_and($ip, $netmask);

				// GMP doesn't have the kind of ~ we're looking for. But
				// that's fine; binary is easy.
				$bin = \gmp_strval(\gmp_init($netmask, 10), 2);
				$bin = \sprintf('%0128s', $bin);
				$bin = \strtr($bin, array('0'=>'1', '1'=>'0'));
				$not = \gmp_strval(\gmp_init($bin, 2), 10);

				$bc = \gmp_or($first, $not);

				// Make sure they're strings.
				$first = \gmp_strval($first);
				$bc = \gmp_strval($bc);
			}
			else {
				$first = bc::bitwise('&', $ip, $netmask);
				$bc = bc::bitwise('|', $first, bc::bitwise('~', $netmask, null, 128));
			}

			$range['min'] = static::number_to_ip($first);
			$range['max'] = static::number_to_ip($bc);

			return $range;
		}

		return false;
	}
1182680
public function ip2longV6($ip)
    {
        if (substr_count($ip, '::')) {
            $ip = str_replace('::', str_repeat(':0000', 8 - substr_count($ip, ':')) . ':', $ip);
        }
        $ip   = explode(':', $ip);
        $r_ip = '';
        foreach ($ip as $v) {
            $r_ip .= str_pad(base_convert($v, 16, 2), 16, 0, STR_PAD_LEFT);
        }

        return base_convert($r_ip, 2, 10);
    }
313682
def in_subnet(cidr, addr=None):
    '''
    
    '''
    try:
        cidr = ipaddress.ip_network(cidr)
    except ValueError:
        log.error('Invalid CIDR \'%s\'', cidr)
        return False

    if addr is None:
        addr = ip_addrs()
        addr.extend(ip_addrs6())
    elif not isinstance(addr, (list, tuple)):
        addr = (addr,)

    return any(ipaddress.ip_address(item) in cidr for item in addr)
1323923
static public function GetIPv4NumberOfHostAddresses($ipAndCidr)
    {

        $ipAndCidrNetwork   = static::ConvertIPv4ToDecimal(
            static::GetIPv4NetworkAddress($ipAndCidr)
        );


        $ipAndCidrBroadcast = static::ConvertIPv4ToDecimal(
            static::GetIPv4BroadcastAddress($ipAndCidr)
        );

        return $ipAndCidrBroadcast - $ipAndCidrNetwork - 1;

    }
470448
private function hostCalculation($format, $separator = '')
    {
        $network_quads = [
            sprintf("$format", $this->quads[0] & ~($this->subnet_mask >> 24)),
            sprintf("$format", $this->quads[1] & ~($this->subnet_mask >> 16)),
            sprintf("$format", $this->quads[2] & ~($this->subnet_mask >>  8)),
            sprintf("$format", $this->quads[3] & ~($this->subnet_mask >>  0)),
        ];

        return implode($separator, $network_quads);
    }
408628
private function prepareNetworkFilter($ip_address)
    {
        $ipv4 = filter_var($ip_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4);
        $ipv6 = filter_var($ip_address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);

        if ($ipv4) {
            $result = function ($network, $ip_address) {
                // Wildcard
                if (strpos($network, '*')) {
                    $allowed_ip_arr = explode('.', $network);
                    $ip_arr = explode('.', $ip_address);
                    for ($i = 0; $i < count($allowed_ip_arr); ++$i) {
                        if ($allowed_ip_arr[$i] == '*') {
                            return true;
                        } else {
                            if (false == ($allowed_ip_arr[$i] == $ip_arr[$i])) {
                                return false;
                            }
                        }
                    }
                }

                // Mask or CIDR
                if (strpos($network, '/')) {
                    $tmp = explode('/', $network);
                    if (strpos($tmp[1], '.')) {
                        list($allowed_ip_ip, $allowed_ip_mask) = explode('/', $network);
                        $begin = (ip2long($allowed_ip_ip) & ip2long($allowed_ip_mask)) + 1;
                        $end = (ip2long($allowed_ip_ip) | (~ip2long($allowed_ip_mask))) + 1;
                        $ip = ip2long($ip_address);

                        return $ip >= $begin && $ip <= $end;
                    } else {
                        list($net, $mask) = explode('/', $network);

                        return (ip2long($ip_address) & ~((1 << (32 - $mask)) - 1)) == ip2long($net);
                    }
                }

                // Section
                if (strpos($network, '-')) {
                    list($begin, $end) = explode('-', $network);
                    $begin = ip2long($begin);
                    $end = ip2long($end);
                    $ip = ip2long($ip_address);

                    return $ip >= $begin && $ip <= $end;
                }

                // Single
                if (ip2long($network)) {
                    return ip2long($network) == ip2long($ip_address);
                }

                return false;
            };
        } elseif ($ipv6) {
            $result = function ($network, $ip_address) {

                // CIDR
                if (strpos($network, '/')) {

                    // Split in address and prefix length
                    list($firstaddrstr, $prefixlen) = explode('/', $network);

                    // Parse the address into a binary string
                    $firstaddrbin = inet_pton($firstaddrstr);

                    // Convert the binary string to a string with hexadecimal characters
                    // unpack() can be replaced with bin2hex()
                    // unpack() is used for symmetry with pack() below
                    $firstaddrhex = reset(unpack('H*', $firstaddrbin));

                    // Calculate the number of 'flexible' bits
                    $flexbits = 128 - $prefixlen;

                    // Build the hexadecimal string of the last address
                    $lastaddrhex = $firstaddrhex;

                    // We start at the end of the string (which is always 32 characters long)
                    $pos = 31;
                    while ($flexbits > 0) {
                        // Get the character at this position
                        $orig = substr($lastaddrhex, $pos, 1);

                        // Convert it to an integer
                        $origval = hexdec($orig);

                        // OR it with (2^flexbits)-1, with flexbits limited to 4 at a time
                        $newval = $origval | (pow(2, min(4, $flexbits)) - 1);

                        // Convert it back to a hexadecimal character
                        $new = dechex($newval);

                        // And put that character back in the string
                        $lastaddrhex = substr_replace($lastaddrhex, $new, $pos, 1);

                        // We processed one nibble, move to previous position
                        $flexbits -= 4;
                        $pos -= 1;
                    }

                    // Convert the hexadecimal string to a binary string
                    // Using pack() here
                    // Newer PHP version can use hex2bin()
                    $lastaddrbin = pack('H*', $lastaddrhex);

                    $ip_address = inet_pton($ip_address);

                    return (strlen($firstaddrbin) == strlen($lastaddrbin)) && ($ip_address >= $firstaddrbin && $ip_address <= $lastaddrbin);
                }

                // Single
                if (filter_var($network, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
                    return inet_pton($ip_address) == inet_pton($network);
                }

                return false;
            };
        } else {
            return false;
        }

        return $result;
    }
1119253
public function getDescription(): string
    {
        if (!empty($this->networkRange)) {
            $message = $this->networkRange['min'];
            if (isset($this->networkRange['max'])) {
                $message .= '-' . $this->networkRange['max'];
            } else {
                $message .= '/' . long2ip((string)bindec($this->networkRange['mask']));
            }
            return __('must be an IP address in the "%s" range', $message);
        }
        return __('must be an IP address');
    }
1218672
public function toIPv4()
    {
        $result = null;
        if (strpos($this->longAddress, '2002:') === 0) {
            $result = IPv4::fromBytes(array_slice($this->getBytes(), 2, 4));
        }

        return $result;
    }
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)
306082
public static function getSubnet($ip, $prefix = 64)
    {
        if (!filter_var($ip, FILTER_VALIDATE_IP)) {
            throw new \InvalidArgumentException('Invalid IP: ' . $ip);
        }

        // Packed representation of IP
        $ip = inet_pton($ip);

        // Maximum netmask length = same as packed address
        $len = 8*strlen($ip);
        if ($prefix > $len) $prefix = $len;

        $mask  = str_repeat('f', $prefix>>2);

        switch($prefix & 3)
        {
            case 3: $mask .= 'e'; break;
            case 2: $mask .= 'c'; break;
            case 1: $mask .= '8'; break;
        }
        $mask = str_pad($mask, $len>>2, '0');

        // Packed representation of netmask
        $mask = pack('H*', $mask);
        // Bitwise - Take all bits that are both 1 to generate subnet
        $subnet = inet_ntop($ip & $mask);

        return $subnet;
    }