Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 890
Rajan Avatar asked Dec 02 '22 02:12

Rajan


2 Answers

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

Here's a snippet for you:

public static String getNextIPV4Address(String ip) {
    String[] nums = ip.split("\\.");
    int i = (Integer.parseInt(nums[0]) << 24 | Integer.parseInt(nums[2]) << 8
          |  Integer.parseInt(nums[1]) << 16 | Integer.parseInt(nums[3])) + 1;

    // If you wish to skip over .255 addresses.
    if ((byte) i == -1) i++;

    return String.format("%d.%d.%d.%d", i >>> 24 & 0xFF, i >> 16 & 0xFF,
                                        i >>   8 & 0xFF, i >>  0 & 0xFF);
}

Examples input / output (ideone.com demonstration):

10.1.1.0        -> 10.1.1.1
10.255.255.255  -> 11.0.0.0
10.0.255.254    -> 10.1.0.0
like image 142
aioobe Avatar answered Dec 05 '22 10:12

aioobe


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"));
}
like image 44
Sean Patrick Floyd Avatar answered Dec 05 '22 09:12

Sean Patrick Floyd