note 80642 modified in function.ip2long by danbrown
| From: | danbrown@php.net | Date: | Fri, 05 Dec 2008 13:32:36 +0000 |
| Subject: | note 80642 modified in function.ip2long by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-147685@lists.php.net to get a copy of this message | ||
A common way to express IP addresses and subnet masks is to use what is refered to as slash
notation. Instead of writing out:
IP = 192.168.100.2
Subnet Mask = 255.255.240.0
Writing out "192.168.100.2/20" is much shorter.
If you are looking for a way to convert a subnet mask into it's slash notation counterpart,
here is a single line of code that can perform this task.
<?php
$slash_notation = strlen(preg_replace("/0/", "",
decbin(ip2long($subnet_mask))));
?>
For example...
A subnet mask of 255.255.240.0 expressed in binary looks like this:
11111111111111111111000000000000
This gives us a slash notation of 20 which is simply counting the number of 1's in the masks
binary representation.
Here is a function that uses this code to return an IP address and subnet mask in slash notation.
<?php
function slash_notation($ip, $mask) {
return $ip."/".strlen(preg_replace("/0/", "",
decbin(ip2long($mask))));
}
?>
calling slash_notation("192.168.100.2", "255.255.255.0"); will return
"192.168.100.2/24".
Hope this is of use to some of you out there.
--was--
A common way to express IP addresses and subnet masks is to use what is refered to as slash
notation. Instead of writing out:
IP = 192.168.100.2
Subnet Mask = 255.255.240.0
Writing out "192.168.100.2/20" is much shorter.
If you are looking for a way to convert a subnet mask into it's slash notation counterpart,
here is a single line of code that can perform this task.
$slash_notation = strlen(preg_replace("/0/", "",
decbin(ip2long($subnet_mask))));
For example...
A subnet mask of 255.255.240.0 expressed in binary looks like this:
11111111111111111111000000000000
This gives us a slash notation of 20 which is simply counting the number of 1's in the masks
binary representation.
Here is a function that uses this code to return an IP address and subnet mask in slash notation.
function slash_notation($ip, $mask) {
return $ip."/".strlen(preg_replace("/0/", "",
decbin(ip2long($mask))));
}
calling slash_notation("192.168.100.2", "255.255.255.0"); will return
"192.168.100.2/24".
Hope this is of use to some of you out there.
http://php.net/manual/en/function.ip2long.php