Oracle中IP转Long 和java中IP转Long

前端之家收集整理的这篇文章主要介绍了Oracle中IP转Long 和java中IP转Long前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. 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})$')) then  
     ip_num_hex := lpad(trim(to_char(regexp_replace(ip,3})$','/1'),'XX')),2,'0') ||  
                   lpad(trim(to_char(regexp_replace(ip,'/2'),'/3'),'/4'),'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,5,7,'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();  
    }
原文链接:https://www.f2er.com/oracle/211218.html

猜你在找的Oracle相关文章