Oracle:将IPv4地址转换为数字?

时间:2014-12-02 22:45:48

标签: oracle ip

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

2 个答案:

答案 0 :(得分:6)

  • 使用regexp_substr。
  • 提取地址的四个八位字节
  • 通过将八位字节移回其原始位置来重构该值。

regexp可能相对昂贵,所以如果你这么做很多,你可以考虑将表中的数值与IP地址一起缓存。

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 

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

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                                                                                                                                                                                                                                                     

答案 1 :(得分:0)

我的需求主要是int> IP,偶尔会有负数int。对于负值,马克的答案不起作用。每个八位位组均以负数形式返回。

这是我想出的对正整数和负整数都有效的方法,至少对于我看过的例子来说如此。 (这适用于除SQL Server以外的大多数数据库-您需要在其中使用'%'函数。)

pip install docx

用于计算负数的mod的方法来自此处: Mod negative numbers in SQL just like excel

相关问题