Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Network Functions : inet_pton

inet_pton

Converts a human readable IP address to its packed in_addr representation (PHP 5 >= 5.1.0)
string inet_pton ( string address )

Example 1605. inet_pton() Example

<?php
$in_addr
= inet_pton('127.0.0.1');

$in6_addr = inet_pton('::1');

?>

Code Examples / Notes » inet_pton

eric

Not so easy in the function below... It is not handling the case of '::' which can happen in an IPv6 and represents any number of 0, addresses could be as simple as ff05::1

me

If you want to use the above function you should test for ':' character before '.'. Meaning, you should check if it's an ipv6 address before checking for ipv4.
Why? IPv6 allows this type of notation:
::127.0.0.1
If you check for '.' character you will think this is an ipv4 address and it will fail.


djmaze

If you need the functionality but your PHP version doesn't have the functionality (like on windows) the following might help
<?php
function inet_pton($ip)
{
# ipv4
if (strpos($ip, '.') !== FALSE) {
$ip = pack('N',ip2long($ip));
}
# ipv6
elseif (strpos($ip, ':') !== FALSE) {
$ip = explode(':', $ip);
$res = str_pad('', (4*(8-count($ip))), '0000', STR_PAD_LEFT);
foreach ($ip as $seg) {
$res .= str_pad($seg, 4, '0', STR_PAD_LEFT);
}
$ip = pack('H'.strlen($res), $res);
}
return $ip;
}
?>


Change Language


Follow Navioo On Twitter
checkdnsrr
closelog
debugger_off
debugger_on
define_syslog_variables
dns_check_record
dns_get_mx
dns_get_record
fsockopen
gethostbyaddr
gethostbyname
gethostbynamel
getmxrr
getprotobyname
getprotobynumber
getservbyname
getservbyport
header
headers_list
headers_sent
inet_ntop
inet_pton
ip2long
long2ip
openlog
pfsockopen
setcookie
setrawcookie
socket_get_status
socket_set_blocking
socket_set_timeout
syslog
eXTReMe Tracker