I'm looking to convert a cidr prefix (e.g. /28) to a netmask (e.g. 255.255.255.240) and have not located a function for this, does one exist in php? If not, how would I go about doing this?
Asked
Active
Viewed 1.1k times
7
-
It is primitive math. Can be easily implemented in few minutes. – zerkms Apr 19 '11 at 02:15
-
Btw, http://stackoverflow.com/questions/4931721/getting-list-ips-from-cidr-notation-in-php – zerkms Apr 19 '11 at 02:16
-
nvm, got it: Got it! $cidr_mask = 24; $bin = ''; for($i=1;$i<=32;$i++) { $bin .= $cidr_mask >= $i ? '1' : '0'; } $netmask = bindec($bin); echo long2ip($netmask); – phpnoobipv4 Apr 19 '11 at 02:24
2 Answers
6
Example #1:
function cidr2NetmaskAddr()
function cidr2NetmaskAddr ($cidr) {
$ta = substr ($cidr, strpos ($cidr, '/') + 1) * 1;
$netmask = str_split (str_pad (str_pad ('', $ta, '1'), 32, '0'), 8);
foreach ($netmask as &$element)
$element = bindec ($element);
return join ('.', $netmask);
}
Usage
echo cidr2NetmaskAddr ('194.234.213.0/28');
Output
255.255.255.240
Example #2:
function createNetmaskAddr()
function createNetmaskAddr ($bitcount) {
$netmask = str_split (str_pad (str_pad ('', $bitcount, '1'), 32, '0'), 8);
foreach ($netmask as &$element)
$element = bindec ($element);
return join ('.', $netmask);
}
Usage
echo createNetmaskAddr (28);
Output
255.255.255.240

Wh1T3h4Ck5
- 8,399
- 9
- 59
- 79