IPV4的地址,我们可以通过ip2long将IP地址转换为INT类型,通过long2ip函数将INT转换为IP地址 $ip = $_SERVER['REMOTE_ADDR']; $ipnum = ip2long($ip); echo $ipnum; IPV6不用使用ip2long函数,使用下面方便处理 1、将php.ini文件中php_gmp.dll扩展打开之后重启服务 2、IPV6转换为INT函数 function ip2long_v6($ipv6) { $ip_n = inet_pton($ipv6); $bits = 15; // 16 x 8 bit = 128bit $ipv6long=''; while ($bits >= 0) { $bin = sprintf("%08b",(ord($ip_n[$bits]))); $ipv6long = $bin.$ipv6long; $bits--; } return gmp_strval(gmp_init($ipv6long,2),10); } 2、把转的数字反转义成ip function long2ip_v6($dec) { if (function_exists('gmp_init')) { $bin = gmp_strval(gmp_init($dec, 10), 2); } elseif (function_exists('bcadd')) { $bin = ''; do { $bin = bcmod($dec, '2') . $bin; $dec = bcdiv($dec, '2', 0); } while (bccomp($dec, '0')); } else { trigger_error('GMP or BCMATH extension not installed!', E_USER_ERROR); } $bin = str_pad($bin, 128, '0', STR_PAD_LEFT); $ip = array(); for ($bit = 0; $bit <= 7; $bit++) { $bin_part = substr($bin, $bit * 16, 16); $ip[] = dechex(bindec($bin_part)); } $ip = implode(':', $ip); return inet_ntop(inet_pton($ip)); } Loading... IPV4的地址,我们可以通过ip2long将IP地址转换为INT类型,通过long2ip函数将INT转换为IP地址 $ip = $_SERVER['REMOTE_ADDR']; $ipnum = ip2long($ip); echo $ipnum; IPV6不用使用ip2long函数,使用下面方便处理 1、将php.ini文件中php_gmp.dll扩展打开之后重启服务 2、IPV6转换为INT函数 function ip2long_v6($ipv6) { $ip_n = inet_pton($ipv6); $bits = 15; // 16 x 8 bit = 128bit $ipv6long=''; while ($bits >= 0) { $bin = sprintf("%08b",(ord($ip_n[$bits]))); $ipv6long = $bin.$ipv6long; $bits--; } return gmp_strval(gmp_init($ipv6long,2),10); } 2、把转的数字反转义成ip function long2ip_v6($dec) { if (function_exists('gmp_init')) { $bin = gmp_strval(gmp_init($dec, 10), 2); } elseif (function_exists('bcadd')) { $bin = ''; do { $bin = bcmod($dec, '2') . $bin; $dec = bcdiv($dec, '2', 0); } while (bccomp($dec, '0')); } else { trigger_error('GMP or BCMATH extension not installed!', E_USER_ERROR); } $bin = str_pad($bin, 128, '0', STR_PAD_LEFT); $ip = array(); for ($bit = 0; $bit <= 7; $bit++) { $bin_part = substr($bin, $bit * 16, 16); $ip[] = dechex(bindec($bin_part)); } $ip = implode(':', $ip); return inet_ntop(inet_pton($ip)); } 最后修改:2019 年 12 月 23 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 支持就是力量