19

Possible Duplicate:
What type should I store IP addresses for MySQL?

One single datatype which can accommodate both IPv4 and IPv6 addresses. I want to store IP addresses to limit the number of profiles that a person can make from his/her machine in my website.

Community
  • 1
  • 1
Robbie Dc
  • 641
  • 2
  • 8
  • 16

2 Answers2

17

IPv4 addresses use 32 bits (4 bytes), IPv6 addresses use 128 bits (16 bytes). Thus, you can store their binary representation in BINARY(16) or VARBINARY(16) fields.

Also see my answer to the question IP address storing in mysql database. It also provides comments why you would choose one over the other.

Community
  • 1
  • 1
knittl
  • 246,190
  • 53
  • 318
  • 364
  • the storage and retrieval works cool... but am not sure whether it will work cool for the intended purpose that I mentioned in the question – Robbie Dc Nov 17 '11 at 06:15
  • 2
    `varbinary(16)` seems to be the best choice. `INET6_ATON('172.32.x.x')` can convert both IPv4 and IPv6 addresses into `blob`. The same can be converted back using `INET6_NTOA`. There won't be any need to juggle code between v4 and v6; at least for storage and retrieval. – Tirtha R Apr 10 '18 at 18:42
  • how to translate this varbinary back into the readable form ? – bansal Jun 20 '18 at 11:32
  • @Abhi there's utility function in many languages, for example in PHP there's `inet_pton`/`inet_ntop` – knittl Jun 20 '18 at 17:20
  • 2
    careful, you can **NOT** reliably store both ipv4 and ipv6 addresses in BINARY(16) - sure, you can *guess* that if the last 12 bytes are null's, then it's *probably* a ipv4 address, but with this guessing, about 4.2 billion ipv6 addresses will be falsely identified as ipv4! (on the other hand, 4.2 billion ipv6 addresses is about 0.00000002% of the total ipv6 space, but it's still a bug, just one presumably very hard to hit) – hanshenrik Nov 01 '19 at 23:24
0

A trie datatype would be optimal. There is uncompressed and compressed data struture from that type.

Micromega
  • 12,486
  • 7
  • 35
  • 72