1、问题

如何将Hive表中的整型ip转成字符串(IP地址)?
3232238099 转成 192.168.10.19

2、背景

整数型的ip:其实是网络序列IP地址(inet_aton函数返回)

在做需求的时候,有两张表
其中A表的ip字段是IP地址字符串(192.168.10.19
B表的ip字段是整型(3232238099
需要自己手动将一张表的数据转成另外一张进行关联。

3、其他代码中的解决方案

Php中:ip2long 和 long2ip
MySQL中:inet_ntoa 和 inet_aton

其他类似,不赘述

4、SQL实现

  1. hive (default)> select
  2. > concat(floor(3232238099 / 16777216)
  3. > ,'.',floor(3232238099 / 65536 % 256)
  4. > ,'.',floor(3232238099 / 256 % 256)
  5. > ,'.',floor(3232238099 % 256)
  6. > )
  7. > ;
  8. OK
  9. 192.168.10.19
  10. Time taken: 0.845 seconds, Fetched: 1 row(s)
  11. hive (default)>

其中

16777216 = 0x1000000
65536 = 0x10000
256 = 0x100

使用MySQL校验,结果如下,校验通过

  1. select inet_ntoa(3232238099);
  2. --------------------
  3. 192.168.10.19

快速实现可以使用这种方式,最好的办法是将ip相关的常用函数写错UDF,方便其他人使用。

5、参考

https://my.oschina.net/goal/blog/198049
https://blog.csdn.net/qinrenzhi/article/details/95375042
https://blog.51cto.com/unicom/2170912