SQL: binary for IP address

I am trying to convert a binary IP address to a public IP address

SELECT HEX( `ip_bin` ) FROM `log_metadata`

gives me   4333D26E000000000000000000000000

AND

SELECT INET_NTOA(0x4333D26E)

gives me 67.51.210.110

So I tried:

SELECT
  SUBSTRING( CONVERT(HEX(`ip_bin`), CHAR(32)), 1, 8 ) AS `A`
, INET_NTOA( 
  SUBSTRING( CONVERT(HEX(`ip_bin`), CHAR(32)), 1, 8 ) 
                                                     ) AS `B`
, INET_NTOA(hex(`ip_bin`))  AS `C`
, INET_NTOA(`ip_bin`)       AS `D`
FROM `log_metadata`

But I only get

+----------+------------+------------+---------+
| A        | B          | C          | D       |
+----------+------------+------------+---------+
| 4333D26E | 0.0.16.237 | 0.0.16.237 | 0.0.0.0 |
+----------+------------+------------+---------+

Any suggestions?

+5
source share
3 answers
mysql> select inet_ntoa(conv('4333d26e', 16, 10));
+-------------------------------------+
| inet_ntoa(conv('4333d26e', 16, 10)) |
+-------------------------------------+
| 67.51.210.110                       |
+-------------------------------------+
1 row in set (0.00 sec)

Check if it works there too =)

Edit

The problem is that it inet_ntoaseems to be analyzing the decimal representation of the number strings, not the hexadecimal, or from the hexadecimal integers. For comparison:

mysql> select inet_ntoa(0x4333d26e);
+-----------------------+
| inet_ntoa(0x4333d26e) |
+-----------------------+
| 67.51.210.110         |
+-----------------------+
1 row in set (0.02 sec)

mysql> select inet_ntoa('0x4333d26e');
+-------------------------+
| inet_ntoa('0x4333d26e') |
+-------------------------+
| 0.0.0.0                 |
+-------------------------+
1 row in set, 1 warning (0.00 sec)

Edit

This is simpler and seems to work too:

SELECT INET_NTOA(CONV(ip_bin, 2, 10)) FROM log_metadata
+2
source

I found what I had to call HEXto convert my binary field to a hexadecimal string first, so the following worked for me:

select inet_ntoa(conv(HEX(ip_bin), 16, 10)) from log_metadata
+3
source

When using Mysql 5.6.3 or later, it's easier to just use it INET6_NTOA- it takes a binary string and returns a human readable format for it. It also supports both IPv4 and IPv6 addresses and accordingly returns the format. Therefore, in your example, you will use:

SELECT INET6_NTOA( `ip_bin` ) FROM `log_metadata`

And should get a readable result.

+1
source

All Articles