我想在我的数据库中存储 IP 地址,但我还需要在整个应用程序中使用它们。我读到了在我的 MySQL 查询中使用 INET_ATON()
和 INET_NTOA()
从 IP 地址中获取 32 位无符号整数,这正是我想要的它将比使用 char(15) 更快地搜索数据库。
问题是,我找不到在 PHP 中做同样事情的函数。我唯一遇到的是:
http://php.net/manual/en/function.ip2long.php
所以我测试了它:
$ip = $_SERVER['REMOTE_ADDR'];
echo ip2long($ip);
它什么也不输出。在他们给出的示例中,它似乎有效,但我又不确定 ip2long()
是否与 INET_ATON()
做同样的事情。
有人知道可以执行此操作的 PHP 函数吗?或者甚至是在数据库中存储 IP 地址的全新解决方案?
谢谢。
最佳答案
ip2long
、long2ip
和 MySQL 函数之间有一个重要的区别。
PHP 的 ip2long
和 long2ip
处理有符号整数。
见 http://php.net/manual/en/function.ip2long.php
"Because PHP's integer type is signed, and many IP addresses will result in negative integers on 32-bit architectures, you need to use the '%u' formatter of sprintf() or printf() to get the string representation of the unsigned IP address."
MySQL 的 INET_ATON()
和 INET_NTOA()
处理无符号整数
见 http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_inet-aton
"To store values generated by INET_ATON(), use an INT UNSIGNED column rather than INT, which is signed. If you use a signed column, values corresponding to IP addresses for which the first octet is greater than 127 cannot be stored correctly."
您可以使用以下一些函数在两者之间工作。
如果您使用 INET_ATON()
将 IP 插入 MySQL 数据库,则可以使用以下命令将其转换回 PHP:
long2ip(sprintf("%d", $ip_address));
您可以使用以下方法将其转换为从 PHP 将其保存在数据库中:
sprintf("%u", ip2long($ip_address));
(同样重要的是,不要将 $ip_address
类型转换为 int
,因为如果数字大于 MAX_INT
。如果必须强制转换,请将其转换为 long
或 float
)
关于php - PHP 中的 INET_ATON() 和 INET_NTOA()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2754340/