百度空间 | 百度首页 
 
查看文章
 
Java中 IP和长整形的转换 [ip2long]
2007-01-31 00:09 A.M.

最近用到了动网的IP库,但是数据库字段用long类型存放,因为动网用的是php系统,php里有一个直接的ip2long的方法。但是java就需要DIY.

import java.net.*;//导入包

public class ip2long {
public static int str2Ip(String ip) throws UnknownHostException {
InetAddress address = InetAddress.getByName(ip);//在给定主机名的情况下确定主机的 IP 址。
byte[] bytes = address.getAddress();//返回此 InetAddress 对象的原始 IP 地址
int a, b, c, d;
a = byte2int(bytes[0]);
b = byte2int(bytes[1]);
c = byte2int(bytes[2]);
d = byte2int(bytes[3]);
int result = (a << 24) | (b << 16) | (c << 8) | d;
return result;
}

public static int byte2int(byte b) {
int l = b & 0x07f;
if (b < 0) {
l |= 0x80;
}
return l;
}

public static long ip2long(String ip) throws UnknownHostException {
int ipNum = str2Ip(ip);
return int2long(ipNum);
}

public static long int2long(int i) {
long l = i & 0x7fffffffL;
if (i < 0) {
l |= 0x080000000L;
}
return l;
}

public static String long2ip(long ip) {
int[] b = new int[4];
b[0] = (int) ( (ip >> 24) & 0xff);
b[1] = (int) ( (ip >> 16) & 0xff);
b[2] = (int) ( (ip >> 8) & 0xff);
b[3] = (int) (ip & 0xff);
String x;
Integer p;
p = new Integer(0);
x = p.toString(b[0]) + "." + p.toString(b[1]) + "." + p.toString(b[2]) +
"." + p.toString(b[3]);

return x;

}
//测试函数
public static void main(String[] args) throws Exception {
long ip = ip2long("1.0.0.0");
System.out.println(ip);
System.out.println(long2ip(ip));

}

}

  

类别:Java | 添加到搜藏 | 浏览() | 评论 (11)
 
网友评论:
1
2007-01-31 00:55 A.M. | 回复
不懂~ 要继续学习
 
2
2007-01-31 01:41 A.M. | 回复
坐板凳~
 
3
2007-01-31 11:09 A.M. | 回复
哈哈,学习一下,另外我的空间也很有意思,欢迎大家光临`
 
4
2007-01-31 02:16 P.M. | 回复
还没学,不明白!
 
5
2007-01-31 04:45 P.M. | 回复
最好自己的事,比抱怨什么都好!第1次说话!
 
6
2007-01-31 08:43 P.M. | 回复
偶不懂,不过看着跟C差不多,偶要把C学好再说,呵呵~~
 
7
2007-02-01 02:48 A.M. | 回复
第一次拜访你的空间,很有特色!谢谢!
 
8
2007-02-01 10:57 A.M. | 回复
so Bit it~~
 
9
2007-02-01 08:58 P.M. | 回复
好久没来了 似乎比漂亮了 蓝色感觉更清新
 
10
2007-02-04 03:53 A.M. | 回复
空间模板更新了,请提宝贵意见和建议!
 
11
2007-02-04 11:27 A.M. | 回复
好深奥啊! 但是还是要支持一下!呵呵~~
 
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码: 请点击后输入四位验证码,字母不区分大小写
      

     

©2009 Baidu