4

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.

aioobe
  • 413,195
  • 112
  • 811
  • 826
Rajan
  • 626
  • 3
  • 8
  • 18

7 Answers7

8

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
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • Won't that function return the subnet address for .254 addresses? 192.168.0.254 -> 192.168.1.0? `arr[index] = "0"` should be `arr[index] = index == 3 ? arr[index] = "1" : arr[index] = "0";`, no? – Till Jun 09 '11 at 16:05
  • Depends on how you define "next" ip address :-) – aioobe Jun 09 '11 at 16:12
  • That's true. Maybe i was assuming too much by thinking he would need usable ip addresses :) – Till Jun 09 '11 at 16:19
  • @Till heheh yeah. That would be assuming too much ;) ...jk. updated the answer. – aioobe Jun 09 '11 at 16:26
4

IP addresses aren't "sequential", so I doubt you'll find a library to do it for you.

dty
  • 18,795
  • 6
  • 56
  • 82
4

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"));
}
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
3

An IP address is pretty much just a 32-bit integer. Depending on how you are storing it, it may be possible to simply increment this underlying value. This probably won't be very reliable however as you have to consider subnets, different address classes etc.

As dty points out, IP addresses aren't sequential, so I wouldn't imagine there is any kind of 'formal' way of doing this.

mdm
  • 12,480
  • 5
  • 34
  • 53
1

Split by ., cast last element to int and increment it. Check whether its value is less than 254 or you will win yourself a broadcast address. Pray that you're always dealing with full class C subnets.

Till
  • 3,084
  • 17
  • 18
0

If using 3rd party libraries is OK, Guava can be used to get the next (or any number after an) IP address like this:

InetAddress a = InetAddresses.forString("192.168.1.1");
int i = InetAddresses.coerceToInteger(a);
InetAddress b = InetAddresses.fromInteger(i+1);
String s = InetAddresses.toAddrString(b);
System.out.println(s);
Hamid Fadishei
  • 830
  • 2
  • 10
  • 16
0

Split the string by "." and convert the 4 strings to bytes. Multiply all the bytes to get int multiplication. Increase the result. Restore bytes by dividing the integer and storing mod in each byte. Convert the bytes to strings and concat all the strings.

StanislavL
  • 56,971
  • 9
  • 68
  • 98