java中int、string、byte数组类型ip地址相互转化

网络编程经常会涉及到int、string、byte数组类型的ip地址相互转化,为了方便使用,写了个类。

其中涉及到的方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

public static String (int ip) {
StringBuffer sb=new StringBuffer();
int b=(ip>>0)&0xff;
sb.append(b+".");
b=(ip>>8)&0xff;
sb.append(b+".");
b=(ip>>16)&0xff;
sb.append(b+".");
b=(ip>>24)&0xff;
sb.append(b);
return sb.toString();
}
//string转int
public static int string2int(String ip) {
String[] ss=ip.split("\.");
byte[] bs=new byte[4];
for(int i=0;i<4;++i) {
bs[i]=Integer.valueOf(ss[i]).byteValue();
}
return bytes2int(bs);
}
//int转byte数组
public static byte[] int2bytes(int ip) {
byte[] src = new byte[4];
src[3] = (byte) ((ip>>24) & 0xFF);
src[2] = (byte) ((ip>>16) & 0xFF);
src[1] = (byte) ((ip>>8) & 0xFF);
src[0] = (byte) (ip & 0xFF);
return src;
}
//byte数组转int
public static int bytes2int(byte[] ip) {
int value;
value = (int) ((ip[0] & 0xFF)
| ((ip[1] & 0xFF)<<8)
| ((ip[2] & 0xFF)<<16)
| ((ip[3] & 0xFF)<<24));
return value;
}

有了以上4个方法,各种类型的ip相互转化就很方便了。