Storing IP address in MySQL database (IPv4 AND IPv6)

前端 未结 5 2335
时光取名叫无心
时光取名叫无心 2021-02-15 17:54

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.

Basically, I

5条回答
  •  忘掉有多难
    2021-02-15 18:52

    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'));
    

    and retrieve it back with the function INET_NTOA:

    SELECT INET_NTOA(ipcol) AS ip FROM table;
    

    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

提交回复
热议问题