Search code examples
javaip-addressipv4inetaddress

how to get the next ip address from a given ip in java?


Folks,

Am looking for a Java code snippet, which gives the next address from the given IP.

so getNextIPV4Address("10.1.1.1") returns "10.1.1.2".

String crunching can be done but might end up messy. Is there a much formalized way for doing this.

Thanks for your time.


Solution

  • This will get you started (add error handling, corner cases etc.):

    public static final String nextIpAddress(final String input) {
        final String[] tokens = input.split("\\.");
        if (tokens.length != 4)
            throw new IllegalArgumentException();
        for (int i = tokens.length - 1; i >= 0; i--) {
            final int item = Integer.parseInt(tokens[i]);
            if (item < 255) {
                tokens[i] = String.valueOf(item + 1);
                for (int j = i + 1; j < 4; j++) {
                    tokens[j] = "0";
                }
                break;
            }
        }
        return new StringBuilder()
        .append(tokens[0]).append('.')
        .append(tokens[1]).append('.')
        .append(tokens[2]).append('.')
        .append(tokens[3])
        .toString();
    }
    

    Test case:

    @Test
    public void testNextIpAddress() {
        assertEquals("1.2.3.5", nextIpAddress("1.2.3.4"));
        assertEquals("1.2.4.0", nextIpAddress("1.2.3.255"));
    }