note 80642 added to function.ip2long
| From: | dbemowsk at osu1 dot php dot net | Date: | Sat, 26 Jan 2008 15:41:00 +0000 |
| Subject: | note 80642 added to function.ip2long | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-135430@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.
$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.
----
Server IP: 209.41.74.194
Probable Submitter: 66.190.12.156
----
Manual Page -- http://www.php.net/manual/en/function.ip2long.php
Edit -- https://master.php.net/note/edit/80642
Del: integrated -- https://master.php.net/note/delete/80642/integrated
Del: useless -- https://master.php.net/note/delete/80642/useless
Del: bad code -- https://master.php.net/note/delete/80642/bad+code
Del: spam -- https://master.php.net/note/delete/80642/spam
Del: non-english -- https://master.php.net/note/delete/80642/non-english
Del: in docs -- https://master.php.net/note/delete/80642/in+docs
Del: other reasons-- https://master.php.net/note/delete/80642
Reject -- https://master.php.net/note/reject/80642
Search -- https://master.php.net/manage/user-notes.php