note 93501 added to function.inet-pton
| From: | strata_ranger at hotmail dot com | Date: | Sun, 13 Sep 2009 17:51:38 +0000 |
| Subject: | note 93501 added to function.inet-pton | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-160514@lists.php.net to get a copy of this message | ||
If the input string is not a readable IP address, inet_pton() generates an E_WARNING and returns
FALSE. The same is true for inet_ntop().
Also, inet_pton() does not recognize netmask notation (e.g: "1.2.3.4/24" or
"1:2::3:4/64") in the input string. This differs from how some database systems (like
postgreSQL) support IP address types, so if you need that sort of functionality when processing IP
addresses in PHP you'll have to write it in yourself.
A rough example:
<?php
// Sample IP addresses
$ipaddr = '1.2.3.4/24'; // IPv4 with /24 netmask
$ipaddr = '1:2::3:4/64'; // IPv6 with /64 netmask
// Strip out the netmask, if there is one.
$cx = strpos($ipaddr, '/');
if ($cx)
{
$subnet = (int)(substr($ipaddr, $cx+1));
$ipaddr = substr($ipaddr, 0, $cx);
}
else $subnet = null; // No netmask present
// Convert address to packed format
$addr = inet_pton($ipaddr);
// Let's display it as hexadecimal format
foreach(str_split($addr) as $char) echo str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT);
echo "<br />\n";
// Convert the netmask
if (is_integer($subnet))
{
// Maximum netmask length = same as packed address
$len = 8*strlen($addr);
if ($subnet > $len) $subnet = $len;
// Create a hex expression of the subnet mask
$mask = str_repeat('f', $subnet>>2);
switch($subnet & 3)
{
case 3: $mask .= 'e'; break;
case 2: $mask .= 'c'; break;
case 1: $mask .= '8'; break;
}
$mask = str_pad($mask, $len>>2, '0');
// Packed representation of netmask
$mask = pack('H*', $mask);
}
// Display the netmask as hexadecimal
foreach(str_split($mask) as $char) echo str_pad(dechex(ord($char)), 2, '0', STR_PAD_LEFT);
?>
----
Server IP: 64.71.164.2
Probable Submitter: 67.237.228.46
----
Manual Page -- http://www.php.net/manual/en/function.inet-pton.php
Edit -- https://master.php.net/note/edit/93501
Del: integrated -- https://master.php.net/note/delete/93501/integrated
Del: useless -- https://master.php.net/note/delete/93501/useless
Del: bad code -- https://master.php.net/note/delete/93501/bad+code
Del: spam -- https://master.php.net/note/delete/93501/spam
Del: non-english -- https://master.php.net/note/delete/93501/non-english
Del: in docs -- https://master.php.net/note/delete/93501/in+docs
Del: other reasons-- https://master.php.net/note/delete/93501
Reject -- https://master.php.net/note/reject/93501
Search -- https://master.php.net/manage/user-notes.php