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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:53:45  来源:igfitidea点击:

Which MySQL datatype to use for an IP address?

phpmysqltypesip-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 $_SERVERvariables, 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_ATONand INET_NTOAto convert them:

INET_ATONINET_NTOA它们转换:

INSERT INTO `table` (`ipv4`) VALUES (INET_ATON("127.0.0.1"));
SELECT INET_NTOA(`ipv4`) FROM `table`;

For IPv6 addresses you could use a BINARYinstead:

对于 IPv6 地址,您可以改用 a BINARY

`ipv6` BINARY(16)

And use PHP's inet_ptonand inet_ntopfor conversion:

并使用PHP 的inet_ptonandinet_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 string
    • 192.128.0.15for instance
  • an integer(4 bytes), if you convert the IP address to an integer
    • 3229614095for 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 BETWEENqueries

对于 IPv4 地址,您可以使用 VARCHAR 将它们存储为字符串,但也可以考虑将它们存储为 long integerss INT(11) UNSIGNED。您可以使用 MySQL 的INET_ATON()函数将它们转换为整数表示。这样做的好处是它允许您对它们进行简单的比较,例如BETWEEN查询

INET_ATON() MySQL function

INET_ATON() MySQL 函数