Oracle SQL 模拟MySQL的inet_aton()和inet_ntoa()

 

MySQL提供了一个很方便的功能,可以对IP地址进行数字格式和IPv4地址格式的转换。在数据库中对IP进行数字格式的保存,在进行范围比较的时候非常方便。Oracle没有内置这样的函数,今天自己实现了一个,以备不时之需。

 

样本数据

IPv4格式: 209.207.224.40   对应的数字格式: 3520061480

 

inet_ntoa()

select 
    trunc(ip/16777216)||'.'|| trunc( mod(ip, 16777216)/65536) ||'.'|| trunc(mod(ip,65536)/256)||'.'|| trunc(mod(ip,256)) as ip_address
from
    (select 3520061480 as ip from dual);

 

inet_aton()

select 
    to_number(regexp_replace(ip, '([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})', '\1')) * 16777216 +
    to_number(regexp_replace(ip, '([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})', '\2')) * 65536 +
    to_number(regexp_replace(ip, '([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})', '\3')) * 256 +
    to_number(regexp_replace(ip, '([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})', '\4'))  as ip_number
from
    (select '209.207.224.40' as ip from dual);,

posted on 2012-09-03 14:57  wait4friend  阅读(1561)  评论(0编辑  收藏  举报