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 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计