版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/enterys/article/details/53760552
- Oracle中IP转long 和Long转IP
create or replace function ip2number(ip varchar2)
return number
is
ip_num_hex varchar2(80);
begin
if (regexp_like(ip, '^(/d{1,3})/.(/d{1,3})/.(/d{1,3})/.(/d{1,3})$')) then
ip_num_hex := lpad(trim(to_char(regexp_replace(ip, '^(/d{1,3})/.(/d{1,3})/.(/d{1,3})/.(/d{1,3})$', '/1'), 'XX')),2,'0') ||
lpad(trim(to_char(regexp_replace(ip, '^(/d{1,3})/.(/d{1,3})/.(/d{1,3})/.(/d{1,3})$', '/2'), 'XX')),2,'0') ||
lpad(trim(to_char(regexp_replace(ip, '^(/d{1,3})/.(/d{1,3})/.(/d{1,3})/.(/d{1,3})$', '/3'), 'XX')),2,'0') ||
lpad(trim(to_char(regexp_replace(ip, '^(/d{1,3})/.(/d{1,3})/.(/d{1,3})/.(/d{1,3})$', '/4'), 'XX')),2,'0');
return to_number(ip_num_hex, 'XXXXXXXX');
else
return -1;
end if;
exception
when others then
return -99999999999;
end;
select ip2number('169.254.55.6') from dual;
IP2NUMBER('169.254.55.6')
-------------------------
2852009734
create or replace function number2ip(num number)
return varchar2 is
ip_num_hex varchar2(8);
begin
ip_num_hex := lpad(trim(to_char(num, 'XXXXXXXX')), 8, '0');
return to_number(substr(ip_num_hex, 1, 2), 'XX') || '.' ||
to_number(substr(ip_num_hex, 3, 2), 'XX') || '.' ||
to_number(substr(ip_num_hex, 5, 2), 'XX') || '.' ||
to_number(substr(ip_num_hex, 7, 2), 'XX');
exception
when others then
dbms_output.put_line(sqlerrm);
return null;
end;
select number2ip(2852009734) from dual;
NUMBER2IP(2852009734)
--------------------------------------------------------------------------------
169.254.55.6
2.java中实现方式
/**
* ip地址转成整数.
* @param ip
* @return
*/
public static long ip2long(String ip) {
String[] ips = ip.split("[.]");
long num = 16777216L*Long.parseLong(ips[0]) + 65536L*Long.parseLong(ips[1]) + 256*Long.parseLong(ips[2]) + Long.parseLong(ips[3]);
return num;
}
/**
* 整数转成ip地址.
* @param ipLong
* @return
*/
public static String long2ip(long ipLong) {
//long ipLong = 1037591503;
long mask[] = {0x000000FF,0x0000FF00,0x00FF0000,0xFF000000};
long num = 0;
StringBuffer ipInfo = new StringBuffer();
for(int i=0;i<4;i++){
num = (ipLong & mask[i])>>(i*8);
if(i>0) ipInfo.insert(0,".");
ipInfo.insert(0,Long.toString(num,10));
}
return ipInfo.toString();
}