这位同志写的代码也太看着吃力了,先写两个简单的方法提供点分十进制IP地址和long型的互相转换:
public static long IpToLong(String ip) {
if ( null==ip || ip.trim().length()==0 ) {
throw new IllegalArgumentException();
}
StringTokenizer st = new StringTokenizer(ip, ".");
if ( 4 != st.countTokens() ) {
throw new IllegalArgumentException();
}
int[] bytes = new int[4];
for ( int i=0; i<4; i++ ) {
String str = st.nextToken(".");
try {
bytes[i] = Integer.parseInt(str);
} catch ( NumberFormatException ex ) {
throw new IllegalArgumentException();
}
if ( bytes[0]<0 || bytes[i]>255 ) {
throw new IllegalArgumentException();
}
} return (long)(bytes[0]*256*256*256 + bytes[1]*256*256 +
bytes[2]*256 + bytes[3]);
}public static String LongToIp(long ip) {
return ""+((ip&0xFF000000L)>>24)+"."+((ip&0xFF0000L)>>16+"."
+((ip&0xFF00L)>>8)+"."+(ip&0xFFL);
}在这两个方法工作正确的前提之下,至少可以简化你的main方法,如下:
public static void main(String[] args) {
// 作args参数检查,假设正确
String startIpAddr = args[0];
String endIpAddr = args[1]; long startIp = IpToLong(startIpAddr);
long endIp = IpToLong(endIpAddr); for ( long ip=startIp; ip<=endIp; ip++ ) {
// 这里是你的循环体
}
}
这样不就简单多了?
public static long IpToLong(String ip) {
if ( null==ip || ip.trim().length()==0 ) {
throw new IllegalArgumentException();
}
StringTokenizer st = new StringTokenizer(ip, ".");
if ( 4 != st.countTokens() ) {
throw new IllegalArgumentException();
}
int[] bytes = new int[4];
for ( int i=0; i<4; i++ ) {
String str = st.nextToken(".");
try {
bytes[i] = Integer.parseInt(str);
} catch ( NumberFormatException ex ) {
throw new IllegalArgumentException();
}
if ( bytes[0]<0 || bytes[i]>255 ) {
throw new IllegalArgumentException();
}
} return (long)(bytes[0]*256*256*256 + bytes[1]*256*256 +
bytes[2]*256 + bytes[3]);
}public static String LongToIp(long ip) {
return ""+((ip&0xFF000000L)>>24)+"."+((ip&0xFF0000L)>>16+"."
+((ip&0xFF00L)>>8)+"."+(ip&0xFFL);
}在这两个方法工作正确的前提之下,至少可以简化你的main方法,如下:
public static void main(String[] args) {
// 作args参数检查,假设正确
String startIpAddr = args[0];
String endIpAddr = args[1]; long startIp = IpToLong(startIpAddr);
long endIp = IpToLong(endIpAddr); for ( long ip=startIp; ip<=endIp; ip++ ) {
// 这里是你的循环体
}
}
这样不就简单多了?
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货