How to get the following IP address from given ip in java?

People,

We are looking for a piece of Java code that gives the following address from this IP.

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

Curl can be done, but it can be dirty. Is there a formalized way to do this.

Thank you for your time.

+4
source share
6 answers

This will help you get 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")); } 
+2
source

We are looking for a piece of Java code that gives the following address from this IP.

Here is 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); } 

I / O examples ( ideone.com demo ):

 10.1.1.0 -> 10.1.1.1 10.255.255.255 -> 11.0.0.0 10.0.255.254 -> 10.1.0.0 
+6
source

IP addresses are not "serial", so I doubt that you will find a library to do this for you.

+4
source

An IP address is just a 32-bit integer. Depending on how you save it, it is possible to simply increase this base value. This will probably not be very reliable, since you need to consider subnets, different address classes, etc.

As dty points out, IPs are not consecutive, so I don't think there is any β€œformal” way to do this.

+3
source

Divide by . , discard the last element to int and increment it. Check if its value exceeds 254 or you will receive a broadcast address for yourself. Pray that you are always dealing with full C classes.

+1
source

Divide the string by. and convert 4 lines to bytes. Multiply all bytes to get int multiplication. Increase the result. Recover the bytes by dividing the integer and saving the mod in each byte. Convert bytes to strings and concatenate all strings.

0
source

All Articles