The challenge
Implement a function that receives two IPv4 addresses, and returns the number of addresses between them (including the first one, excluding the last one).
All inputs will be valid IPv4 addresses in the form of strings. The last address will always be greater than the first one.
Examples
ips_between("10.0.0.0", "10.0.0.50") == 50
ips_between("10.0.0.0", "10.0.1.0") == 256
ips_between("20.0.0.10", "20.0.1.0") == 246
The solution in Java code
Option 1:
public class CountIPAddresses {
public static long ipsBetween(String start, String end) {
return convertToLong(end) - convertToLong(start);
}
private static long convertToLong(String ip) {
long res = 0;
for (String s : ip.split("[.]") )
res = res * 256 + Long.parseLong(s);
return res;
}
}
Option 2:
import java.util.Arrays;
public class CountIPAddresses {
public static long ipsBetween(String start, String end) {
long[] o = Arrays.stream(start.split("\\.")).mapToLong(Long::parseLong).toArray();
long[] t = Arrays.stream(end.split("\\.")).mapToLong(Long::parseLong).toArray();
long diff = 0;
for (int i = 0; i < 4; i++) {
diff += (t[i] - o[i]) << (8 * (3-i));
}
return diff;
}
}
Option 3:
public class CountIPAddresses {
public static long ipsBetween(String start, String end) {
long result = 0;
String [] ad1 = start.split("\\.");
String [] ad2 = end.split("\\.");
result += (Long.parseLong(ad2[0]) - Long.parseLong(ad1[0]))*256*256*256;
result += (Long.parseLong(ad2[1]) - Long.parseLong(ad1[1]))*256*256;
result += (Long.parseLong(ad2[2]) - Long.parseLong(ad1[2]))*256;
result += (Long.parseLong(ad2[3]) - Long.parseLong(ad1[3]));
return result;
}
}
Test cases to validate our solution
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class CountIPAddressesTest {
@Test
public void ipsBetween() throws Exception {
assertEquals( 50, CountIPAddresses.ipsBetween( "10.0.0.0", "10.0.0.50" ) );
assertEquals( 246, CountIPAddresses.ipsBetween( "20.0.0.10", "20.0.1.0" ) );
}
}