项目中有个地方要用到导入某个安全系统的数据库进行分析,需要用到里面记录的ip地址,倒过来之后发现ip地址是数值型的,比如190131313 这样开始还以为是没有加“.”呢 一番研究弯路之后才知道原来ip是经过处理了,果然是安全系统,oh shit
百google度之后看到两篇文章值得借鉴 分别是
http://stephen830.iteye.com/blog/254742 java转换ip地址与数值的实现
和http://blog.csdn.net/ngx20080110/article/details/5694146 oracle中ip和数值的转换
oracle中的转换
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
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();
}