哪个 MySQL 数据类型用于 IP 地址?
<块引用>
可能的重复:
如何在 mySQL 中存储 IP
我想从 $_SERVER['REMOTE_ADDR'] 和其他一些 $_SERVER 变量中获取 IP 地址,哪种数据类型适合于此?>
是VARCHAR(n)吗?
由于 IPv4 地址是 4 字节长,您可以使用 INT (UNSIGNED) 正好有 4 个字节:
`ipv4` INT UNSIGNED和 INET_ATON 和 INET_NTOA 转换它们:
INSERT INTO `table` (`ipv4`) VALUES (INET_ATON("127.0.0.1"));SELECT INET_NTOA(`ipv4`) FROM `table`;对于 IPv6 地址,您可以使用 BINARY 代替:
`ipv6` BINARY(16)并使用 PHP 的 inet_pton 和 inet_ntop 用于转换:
'INSERT INTO `table` (`ipv6`) VALUES ("'.mysqli_real_escape_string(inet_pton('2001:4860:a005::68')).'")''从`表`中选择`ipv6`'$ipv6 = inet_pton($row['ipv6']);Possible Duplicate:
How to store an IP in mySQL
I want to get the IP address from $_SERVER['REMOTE_ADDR'] and some other $_SERVER variables, which datatype is the right one for this?
Is it VARCHAR(n)?
Since IPv4 addresses are 4 byte long, you could use an INT (UNSIGNED) that has exactly 4 bytes:
`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` BINARY(16)
And use PHP’s inet_pton and inet_ntop for conversion:
'INSERT INTO `table` (`ipv6`) VALUES ("'.mysqli_real_escape_string(inet_pton('2001:4860:a005::68')).'")'
'SELECT `ipv6` FROM `table`'
$ipv6 = inet_pton($row['ipv6']);
相关文章