Count IP Addresses in Java

1 min read 255 words

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" ) );
	}

}
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts