SQL: Binary to IP Address

回眸只為那壹抹淺笑 提交于 2019-12-04 04:11:36
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 inet_ntoa seems to parse from decimal strings number representation, not hexadecimal ones, or from hexadecimal integers. Compare:

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

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

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

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

SELECT INET6_NTOA( `ip_bin` ) FROM `log_metadata`

And should get the human readable result.

FYI~ this works in newer version of mysql

 SELECT INET6_NTOA( `ip_bin` ) FROM `log_metadata`

which is the same as

SELECT INET_NTOA( CONV( SUBSTRING(HEX(`ip_bin` ), 1, 8), 16, 10 )) FROM log_metadata;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!