posts - 66, comments - 12, trackbacks - 0, articles - 0

获得两个ip段之间的所有ip

Posted on 2008-06-11 13:16 cyantide 阅读(764) 评论(0)  编辑  收藏 所属分类: 网络相关技术
网上摘录的,向作者表示感谢

将IPV4转成32位无符号的数(一个IPV4是一个32位的二进制数),然后处理。
参考代码如下:
Java code
import java.net.*;
import java.nio.*
;
public class
PrintIP { //一个IP,是一个32位无符号的二进制数。故用long的低32表示无符号32位二进制数。
    public static long getIP(InetAddress ip)
{
byte[] b=
ip.getAddress();
long l= b[0]<<24L & 0xff000000L|

                b[
1]<<16L & 0xff0000L  |
                b[
2]<<8L  &  0xff00L   |
                b[
3]<<0L  &  0xffL ;
return
l;
}
//由低32位二进制数构成InetAddress对象

    public static InetAddress toIP(long ip) throws UnknownHostException
{
byte[] b=new byte[4
];
int i=(int)ip;//低32位

        b[0]= (byte)( (i >> 24) & 0x000000ff );
b[
1]= (byte)( (i >> 16) & 0x000000ff
);
b[
2]= (byte)( (i >> 8& 0x000000ff
);
b[
3]= (byte)( (i >> 0& 0x000000ff
);
return
InetAddress.getByAddress(b);
}
public static void main(String[] args) throws
UnknownHostException {
long ip1=getIP(InetAddress.getByName("192.168.0.233"
));
long ip2=getIP(InetAddress.getByName("192.168.1.12"
));
System.out.println(
"192.168.0.233到192.168.1.12之间所有的IP是:"
);
for(long ip=ip1;ip<=ip2;ip++
)
{
System.out.println(toIP(ip).getHostAddress());
}
}
}

程序运行结果:
192.168.0.233到192.168.1.12之间所有的IP是:
192.168.0.233
192.168.0.234
192.168.0.235
192.168.0.236
192.168.0.237
192.168.0.238
192.168.0.239
192.168.0.240
192.168.0.241
192.168.0.242
192.168.0.243
192.168.0.244
192.168.0.245
192.168.0.246
192.168.0.247
192.168.0.248
192.168.0.249
192.168.0.250
192.168.0.251
192.168.0.252
192.168.0.253
192.168.0.254
192.168.0.255
192.168.1.0
192.168.1.1
192.168.1.2
192.168.1.3
192.168.1.4
192.168.1.5
192.168.1.6
192.168.1.7
192.168.1.8
192.168.1.9
192.168.1.10
192.168.1.11
192.168.1.12
因为不知道你的需求中要不要去掉特殊的IP。故程序中没有判特殊IP。
说明:若要去掉网络地址如:192.168.0.0,192.168.1.0,191.12.0.0,12.0.0.0与定向广播地址如:192.168.0.255,192.168.1.255,192.12.255.255,12.255.255.255等,你在程序中再判一下。

只有注册用户登录后才能发表评论。


网站导航: