INET_ATON()和INET_NTOA()在PHP? [英] INET_ATON() and INET_NTOA() in PHP?
问题描述
我想在我的数据库中存储IP地址,但我还需要在我的应用程序中使用它们。我阅读了在我的MySQL查询中使用 INET_ATON()
和 INET_NTOA()
得到一个32位无符号整数的IP地址,这正是我想要的,因为它会使搜索通过数据库比使用char(15)。
I want to store IP addresses in my database, but I also need to use them throughout my application. I read about using INET_ATON()
and INET_NTOA()
in my MySQL queries to get a 32-bit unsigned integer out of an IP address, which is exactly what I want as it will make searching through the database faster than using char(15).
事情是,我不能找到一个函数在PHP中做同样的事情。我遇到的唯一的是:
The thing is, I can't find a function that does the same sort of thing in PHP. The only thing I came across is:
http://php.net/manual/en/function.ip2long.php
所以我测试了它:
$ip = $_SERVER['REMOTE_ADDR'];
echo ip2long($ip);
并不输出任何内容。在这个例子中,它们似乎工作,但是我不知道如果 ip2long()
做同样的事情 INET_ATON
。
And it outputs nothing. In the example they gave it seems to work, but then again I'm not exactly sure if ip2long()
does the same thing as INET_ATON()
.
有人知道一个PHP函数会这样做吗?或者甚至是一个全新的解决方案,在数据库中存储IP地址?
Does someone know a PHP function that will do this? Or even a completely new solution to storing an IP address in a database?
谢谢。
推荐答案
ip2long()
和 long2ip()
函数应该可以正常工作。
The ip2long()
and long2ip()
functions should work just fine.
注意:你应该使用IPv4地址 - 确保在你的情况下, $ _ SERVER ['REMOTE_ADDR']
实际上包含有效的IPv4地址(而不是某些IPv6资料)
Note : you should use those for IPv4 addresses -- make sure that, in your case, $_SERVER['REMOTE_ADDR']
actually contains a valid IPv4 address (and not some IPv6-stuff).
尝试使用Google IP地址:
Trying on a google IP address :
var_dump(ip2long('209.85.227.147'));
var_dump(long2ip(3512066963));
我得到以下输出:
int(3512066963)
string(14) "209.85.227.147"
这篇关于INET_ATON()和INET_NTOA()在PHP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!