Reputation: 1
I am trying to get all the IP addresses between the two addresses("168.200.197.3" and "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). 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);
}
}
}
}
}
Upvotes: 0
Views: 2409
Reputation: 17697
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:
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:
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.
Upvotes: 1
Reputation: 4119
An IPv4 address like a.b.c.d
can be represented by an unsigned integer 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.
Upvotes: 5