php 哪个 MySQL 数据类型用于 IP 地址?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5133580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Which MySQL datatype to use for an IP address?
提问by ComFreek
Possible Duplicate:
How to store an IP in mySQL
可能的重复:
如何在 mySQL 中存储 IP
I want to get the IP address from $_SERVER['REMOTE_ADDR']
and some other $_SERVER
variables, which datatype is the right one for this?
我想从$_SERVER['REMOTE_ADDR']
其他一些$_SERVER
变量中获取 IP 地址,哪种数据类型适合于此?
Is it VARCHAR(n)
?
是VARCHAR(n)
吗?
回答by Gumbo
Since IPv4 addresses are 4 byte long, you could use an INT
(UNSIGNED
)that has exactly 4 bytes:
由于 IPv4 地址的长度为 4 个字节,因此您可以使用正好为 4 个字节的INT
( UNSIGNED
):
`ipv4` INT UNSIGNED
And INET_ATON
and INET_NTOA
to convert them:
INSERT INTO `table` (`ipv4`) VALUES (INET_ATON("127.0.0.1"));
SELECT INET_NTOA(`ipv4`) FROM `table`;
For IPv6 addresses you could use a BINARY
instead:
对于 IPv6 地址,您可以改用 a BINARY
:
`ipv6` BINARY(16)
And use PHP's inet_pton
and inet_ntop
for conversion:
并使用PHP 的inet_pton
andinet_ntop
进行转换:
'INSERT INTO `table` (`ipv6`) VALUES ("'.mysqli_real_escape_string(inet_pton('2001:4860:a005::68')).'")'
'SELECT `ipv6` FROM `table`'
$ipv6 = inet_pton($row['ipv6']);
回答by Pascal MARTIN
You have two possibilities (for an IPv4 address) :
您有两种可能性(对于 IPv4 地址):
- a
varchar(15)
, if your want to store the IP address as a string192.128.0.15
for instance
- an
integer
(4 bytes), if you convert the IP address to an integer3229614095
for the IP I used before
- a
varchar(15)
, 如果您想将 IP 地址存储为字符串192.128.0.15
例如
- an
integer
(4个字节),如果将IP地址转换为整数3229614095
对于我之前使用的 IP
The second solution will require less space in the database, and is probably a better choice, even if it implies a bit of manipulations when storing and retrieving the data (converting it from/to a string).
第二种解决方案将需要较少的数据库空间,并且可能是更好的选择,即使它在存储和检索数据(将其从/转换为字符串)时意味着一些操作。
About those manipulations, see the ip2long()
and long2ip()
functions, on the PHP-side, or inet_aton()
and inet_ntoa()
on the MySQL-side.
关于这些操作,见ip2long()
和long2ip()
功能,在PHP端,或inet_aton()
与inet_ntoa()
对MySQL的边。
回答by Michael Berkowski
For IPv4 addresses, you can use VARCHAR to store them as strings, but also look into storing them as long integesrs INT(11) UNSIGNED
. You can use MySQL's INET_ATON()
function to convert them to integer representation. The benefit of this is it allows you to do easy comparisons on them, like BETWEEN
queries
对于 IPv4 地址,您可以使用 VARCHAR 将它们存储为字符串,但也可以考虑将它们存储为 long integerss INT(11) UNSIGNED
。您可以使用 MySQL 的INET_ATON()
函数将它们转换为整数表示。这样做的好处是它允许您对它们进行简单的比较,例如BETWEEN
查询