What type should I store IP addresses for MySQL?

前端 未结 3 900
遇见更好的自我
遇见更好的自我 2020-12-03 15:34

I was going to use varchar(20), but I was wondering what should if I should do INT and strip off the periods instead. What would be better and why?

3条回答
  •  执笔经年
    2020-12-03 15:43

    I presume you're only interested in IPv4 addresses, not IPv6.

    I would use an INT UNSIGNED for the column, and then use INET_ATON and INET_NTOA to convert back and forth between the textual representation and the int value.

    mysql> SELECT INET_ATON('192.168.10.50');
    +----------------------------+
    | INET_ATON('192.168.10.50') |
    +----------------------------+
    |                 3232238130 |
    +----------------------------+
    1 row in set (0.00 sec)
    
    mysql> SELECT INET_NTOA(3232238130);
    +-----------------------+
    | INET_NTOA(3232238130) |
    +-----------------------+
    | 192.168.10.50         |
    +-----------------------+
    1 row in set (0.00 sec)
    

提交回复
热议问题