views:

277

answers:

2

Hi,

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).

+3  A: 
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.

chaos
+4  A: 

You can use this function,

<?php

function to_netmask($ip, $prefix) {
    $mask = $prefix==0?0:0xffffffff << (32 - $prefix);
    return long2ip(ip2long($ip) & $mask);
}

?>
ZZ Coder