note 80642 deleted from function.ip2long by cmb

From: Date: Sun, 13 Oct 2019 07:52:01 +0000
Subject: note 80642 deleted from function.ip2long by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-212613@lists.php.net to get a copy of this message
Note Submitter: dbemowsk ---- 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.

« previous php.notes (#212613) next »