Reputation: 489
How could I get a /22 network address from an IP address?
Like:
/24 of 193.95.221.54 is 193.95.221.0
/16 of 193.95.221.54 is 193.95.0.0
/8 of 193.95.221.54 is 193.0.0.0
/22 of 193.95.221.54 is 193.95.X.0
I'd like to cache GeoIP data for 1024 IP addresses with a single cache entry to conserve cache space and number of lookups (GeoIP database is 25 MB).
Upvotes: 2
Views: 1138
Reputation: 75466
You can use this function,
<?php
function to_netmask($ip, $prefix) {
$mask = $prefix==0?0:0xffffffff << (32 - $prefix);
return long2ip(ip2long($ip) & $mask);
}
?>
Upvotes: 7
Reputation: 124317
long2ip(ip2long($addr) & 0xf00)
where 0xf00
is the integer where the bits you want to consider are set, e.g. 0xffffff00' for
/24, '0xffff0000
for /16
, etc.
Upvotes: 3