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
inet_pton
(PHP 5 >= 5.1.0)
inet_pton — 人間が読める形式の IP アドレスを、パックされた in_addr 形式に変換する
説明
string inet_pton
( string $address
)
この関数は、人間が読める形式の IPv4 あるいは IPv6 (PHP が IPv6 サポートを有効にしてビルドされている場合) のアドレスを 32 ビットあるいは 128 ビットのバイナリ形式に変換します。
パラメータ
- address
-
可読形式の IPv4 アドレスあるいは IPv6 アドレス。
返り値
指定した address を in_addr 形式で表したものを返します。
例
例1 inet_pton() の例
<?php
$in_addr = inet_pton('127.0.0.1');
$in6_addr = inet_pton('::1');
?>
注意
注意: この関数は Windows 環境にはまだ実装されていません。
inet_pton
eric at vyncke org
19-Jul-2007 02:52
19-Jul-2007 02:52
me at diogoresende dot net
17-May-2006 06:34
17-May-2006 06: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 05:01
14-Dec-2005 05: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;
}
?>