note 104163 added to function.ip2long

From: Date: Sat, 28 May 2011 16:13:42 +0000
Subject: note 104163 added to function.ip2long
Groups: php.notes 
Request: Send a blank email to php-notes+get-180076@lists.php.net to get a copy of this message
In 32bits systems, you cannot convert ipv6 to long, but you can convert ip2bin and bin2ip This function converts ipv4 and ipv6, returns false if ip is not valid <?php function ip2bin($ip) { if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false) return base_convert(ip2long($ip),10,2); if(filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false) return false; if(($ip_n = inet_pton($ip)) === false) return false; $bits = 15; // 16 x 8 bit = 128bit (ipv6) while ($bits >= 0) { $bin = sprintf("%08b",(ord($ip_n[$bits]))); $ipbin = $bin.$ipbin; $bits--; } return $ipbin; } function bin2ip($bin) { if(strlen($bin) == 31) // 32bits (ipv4) return long2ip(base_convert($bin,2,10)); if(strlen($bin) != 128) return false; $pad = 128 - strlen($bin); for ($i = 1; $i <= $pad; $i++) { $bin = "0".$bin; } $bits = 0; while ($bits <= 7) { $bin_part = substr($bin,($bits*16),16); $ipv6 .= dechex(bindec($bin_part)).":"; $bits++; } return inet_ntop(inet_pton(substr($ipv6,0,-1))); } ?> ---- Server IP: 81.92.192.129 Probable Submitter: 188.80.219.23 ---- Manual Page -- http://www.php.net/manual/en/function.ip2long.php Edit -- https://master.php.net/note/edit/104163 Del: integrated -- https://master.php.net/note/delete/104163/integrated Del: useless -- https://master.php.net/note/delete/104163/useless Del: bad code -- https://master.php.net/note/delete/104163/bad+code Del: spam -- https://master.php.net/note/delete/104163/spam Del: non-english -- https://master.php.net/note/delete/104163/non-english Del: in docs -- https://master.php.net/note/delete/104163/in+docs Del: other reasons-- https://master.php.net/note/delete/104163 Reject -- https://master.php.net/note/reject/104163 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#180076) next »