在MySQL数据库中存储IP地址(IPv4和IPv6) [英] Storing IP address in MySQL database (IPv4 AND IPv6)
问题描述
好的,现在我知道类似的问题可能已被问过一百万次,但我是一个真正的新手,我真的很感谢你的帮助。
Ok, now I'm aware that similar questions have probably been asked a million times but I'm a real novice at this and I'd really appreciate your help here.
基本上,我想将访问者的IP地址存储在MySQL中,以便以后检索和验证。我首先需要知道我需要使用哪种类型的字段来存储IP地址。如果可能的话,我还想让系统与IPv6地址兼容。
Basically, I want to store the visitors IP address in a MySQL for later retrieval and verification. I firstly need to know what type of field I need to use to store the IP address in. I would also like to make the system compatible with IPv6 addresses if possible.
在此先感谢
推荐答案
要存储IPv4,您可以使用 INT UNSIGNED
,对于IPv6,你需要一个十进制(39,0),
来在表中存储一个ip,你可以使用函数 INET_ATON
:
To store an IPv4 you can use an INT UNSIGNED
, while for a IPv6 you need a decimal(39,0),
to store an ip in the table you can use the function INET_ATON
:
INSERT INTO table (ipcol) VALUES (INET_ATON('192.168.0.10'));
并使用函数 INET_NTOA
将其检索回来:
and retrieve it back with the function INET_NTOA
:
SELECT INET_NTOA(ipcol) AS ip FROM table;
这是在MySQL IPv6支持之前得到的答案; 用户应该知道MySQL现在本身支持IPv6: https://dev.mysql.com/doc/refman/5.6/en/miscellaneous-functions.html
This answered existing before MySQL IPv6 support; users should be made aware that MySQL now natively supports IPv6: https://dev.mysql.com/doc/refman/5.6/en/miscellaneous-functions.html
这篇关于在MySQL数据库中存储IP地址(IPv4和IPv6)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!