[英]generating all IP address between two IP addresses in java
I am trying to get all the IP addresses between the two addresses("168.200.197.3" and "238.199.200.78"). 我正在尝试获取两个地址之间的所有IP地址(“ 168.200.197.3”和“ 238.199.200.78”)。 I splited the string to integer first.
我先将字符串拆分为整数。 Then i tried to printout all addresses between these two.
然后我试图打印出这两个之间的所有地址。 But the output only shows that each part of the address is being incremented, like 168 169 170...... I want the whole address to be increased(168.200.197.3, 168.200.197.4,168.200.197.5....etc).
但是输出仅显示地址的每个部分都在增加,例如168169170 ......我希望整个地址都增加(168.200.197.3,168.200.197.4,168.200.197.5..etc )。 Please help !!!!!!!
请帮忙 !!!!!!!
public class IpAddress {
public static void main(String[] args) {
int [] ip1 = new int[4];
int [] ip2 = new int[4];
String [] parts1 = "168.200.197.3".split("\\.");
String [] parts2 = "238.199.200.78".split("\\.");
for (int i = 0; i <4; i++){
ip1[i] = Integer.parseInt(parts1[i]);
for (int j = 0; j<4; j ++){
ip2[j] = Integer.parseInt(parts2[j]);
for (int k = ip1[i]; k<ip2[j]; k++){
System.out.println(k);
}
}
}
}
}
An IPv4 address like abcd
can be represented by an unsigned integer a*256^3+b*256^2+c*256+d
. 像
abcd
这样的IPv4地址可以由无符号整数a*256^3+b*256^2+c*256+d
。 Now you can turn the two IP addresses into unsigned integers then you get an integer range, iterate the range and convert each unsigned integer back to IPv4 literal. 现在,您可以将两个IP地址转换为无符号整数,然后获得一个整数范围,迭代该范围并将每个无符号整数转换回IPv4文字。
If it was me I would do this using an int
value to represent the IP address and write a function that converts the int
to a String representation of the IP: 如果是我,我将使用一个
int
值来表示IP地址,并编写一个将int
转换为IP的String表示的函数:
private static final String getIPFromInt(final long ipaslong) {
return String.format("%d.%d.%d.%d",
(ipaslong >>> 24) & 0xff,
(ipaslong >>> 16) & 0xff,
(ipaslong >>> 8) & 0xff,
(ipaslong ) & 0xff);
}
Then I would calculate the start and end points by converting them to int representations (the opposite problem as the getIPFromLong(...) method, which I will leave as an exercise for you) and finally I would write a simple loop: 然后,我将起点和终点转换为int表示形式(与getIPFromLong(...)方法相反的问题,我将作为练习留给您)来计算起点和终点,最后我将编写一个简单的循环:
final long from = getLongFromIP(ip1);
final long to = getLongFromIP(ip2);
for (long i = from; i <= to, i++) {
System.out.println(getIPFromLong(i);
}
EDIT: Changed loop argument i
to be a long, and the other methods to accept long
instead of int
to avoid issues with integer sign bits. 编辑:将循环参数
i
更改为long,其他方法接受long
而不是int
以避免整数符号位出现问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.