Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert IPv6 from binary for storage in MySQL

Tags:

php

mysql

ipv6

I am trying to store IPv6 addresses in MySQL 5.0 in an efficient way. I have read the other questions related to this, such as this one. The author of that question eventually chose for two BIGINT fields. My searches have also turned up another often used mechanism: Using a DECIMAL(39,0) to store the IPv6 address. I have two questions about that.

  1. What are the advantages and disadvantages of using DECIMAL(39,0) over the other methods such as 2*BIGINT?
  2. How do I convert (in PHP) from the binary format as returned by inet_pton() to a decimal string format usable by MySQL, and how do I convert back so I can pretty-print with inet_ntop()?
like image 685
Sander Marechal Avatar asked Jul 13 '09 16:07

Sander Marechal


People also ask

Is IPv6 in binary?

This means that an IPv4 address is made up of 32 1s and 0s while an IPv6 address is made up of 128 of them – 128 binary digits.

Does IPv6 use binary or hexadecimal?

Hexadecimal (the Base16 numbering system), rather than decimal (the Base10 numbering system), is used for IPv6 because it is easier to convert between hexadecimal and binary than it is to convert between decimal and binary. Each hexadecimal digit represents four binary digits.


1 Answers

We went for a VARBINARY(16) column instead and use inet_pton() and inet_ntop() to do the conversions:

https://github.com/skion/mysql-udf-ipv6

The functions can be loaded into a running MySQL server and will give you INET6_NTOP and INET6_PTON in SQL, just as the familiar INET_NTOA and INET_ATON functions for IPv4.

Edit: There are compatible functions in MySQL now, just with different names. Only use the above if you are on pre-5.6 MySQL and are looking for a convenient future upgrade path.

like image 152
Pieter Ennes Avatar answered Sep 19 '22 21:09

Pieter Ennes