dph58509 2015-06-11 00:12
浏览 77
已采纳

将IP存储到mysql数据库中

I'm using a simple way to get the real ip. I found it here: How to get Real IP from Visitor?

The IP will be stored into database, in some column width VARCHAR 15. I'm using Varchar with length 15 because I understand that the ip address can be 123.456.789.123, which has 12 numbers and 3 dots.

Now... I saw that the IPv6 has more chars. I do not understand. All users have a particular IPv4 or may be some users with IPv6 and not IPv4 ?

I need to understand because I want to optimize this column of IP, as I saw here: insert ip into mysql is better to make it decimal.

How to should I make this column decimal if the ip (version 6) can have more than 15 chars ?

I'm confuse...

  • 写回答

1条回答 默认 最新

  • duanjuelu8874 2015-06-11 00:42
    关注

    For handling and storing both IPv4 and IPv6 addresses, you can use datatype VARBINARY(16).

    In version 5.6, MySQL (finally!) introduced conversion functions for IPv6 addresses: INET6_ATON, so you don't have to do the conversion in your application.

    If you are handling only IPv4 addresses, you can continue to use the INET6_ATON function, and BINARY(4) is a suitable datatype for storing it.

    Conveniently, the inverse functions, for converting from the binary representation back to dotted decimal form (for IPv4 addresses) or the hex colon form (for IPv6 addresses) are also available.

    Reference: https://dev.mysql.com/doc/refman/5.6/en/miscellaneous-functions.html#function_inet6-aton

    Q: How to should I make this column decimal if the ip (version 6) can have more than 15 chars ?

    A: Don't make the column DECIMAL, make it VARBINARY(16), and convert both the IPv4 dotted decimal representation, and the IPv6 hex colon representation into a binary representatin to store it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办