Oracle:将IPv4地址转换为数字? [英] Oracle: Converting an IPv4 address to a number?

查看:460
本文介绍了Oracle:将IPv4地址转换为数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将点分十进制格式的IPv4地址转换为数字?例如,地址 39.255.2.51 应转换为 4026466867

How can I convert an IPv4 address in dot-decimal format to a number? For example, the address 39.255.2.51 should be converted to 4026466867.

推荐答案


  • 使用regexp_substr提取地址的四个八位字节。

  • 通过移动八位字节重构该值回到他们原来的位置。

  • 正则表达式可能相对昂贵,所以如果你这么做很多,你可以考虑缓存表格中的数字值与IP地址一起。

    The regexp might be relatively expensive, so if you're doing this a lot you might consider caching the numeric value in your table alongside the IP address.

    with addr as (select '239.255.2.51' ip from dual)
    select ip, to_number(regexp_substr(ip, '\d+', 1, 1)) * 16777216 +
               to_number(regexp_substr(ip, '\d+', 1, 2)) * 65536 +
               to_number(regexp_substr(ip, '\d+', 1, 3)) * 256 +
               to_number(regexp_substr(ip, '\d+', 1, 4)) n
      from addr;
    
    IP                     N
    ------------- ----------      
    239.255.2.51  4026466867 
    

    为了完整性,这里是另一种方式。

    For completeness, here's how to go the other way.

    with addr as (select 4026466867 n from dual)
    select n, mod(trunc(n/16777216),256) ||'.'||
              mod(trunc(n/65536),   256) ||'.'||
              mod(trunc(n/256),     256) ||'.'||
              mod(n,                256) ip
    from addr;
    
             N IP                                                                                                                                                                                                                                                             
    ---------- ------------
    4026466867 239.255.2.51                                                                                                                                                                                                                                                     
    

    这篇关于Oracle:将IPv4地址转换为数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆