且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在MySQL数据库中存储IP地址(IPv4和IPv6)

更新时间:2022-11-27 14:37:25

要存储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