inet_pton

(PHP 5 >= 5.1.0RC1)

inet_pton --  Converts a human readable IP address to its packed in_addr representation

Description

string inet_pton ( string address )

This function converts a human readable IPv4 or IPv6 address (if PHP was built with IPv6 support enabled) into an address family appropriate 32bit or 128bit binary structure.

例子 1. inet_pton() Example

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

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

?>

注: 本函数未在 Windows 平台下实现。

See also ip2long(), inet_ntop(), and long2ip().


add a note add a note User Contributed Notes
me at diogoresende dot net
17-May-2006 05:34
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(AT)dragonflycms(.)org
14-Dec-2005 04:01
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;
}
?>