How to get a range of IP addresses based on start and end IP addresses?

How to create a range of IP addresses from start and end IP addresses?

Example for the network "192.168.0.0/24":

String start = "192.168.0.2" String end = "192.168.0.254" 

I want to have:

 192.168.0.2 192.168.0.3 192.168.0.4 192.168.0.5 ... 192.168.0.254 

PS: The network, start and end IP addresses can be dynamic, this is just an example.

Thanks...

+6
source share
4 answers

Recognize that each of the 4 components of the IPv4 address is indeed a hexadecimal number between 00 and FF.

If you change the starting and ending IP addresses to unsigned 32-bit integers, you can simply go from the lowest to the highest and convert every value that you loop back to the IP address format.

The range in the example is C0A80002 - C0A800FE.

Here's a link to code that translates between a hexadecimal number and an IPv4 address

http://technojeeves.com/joomla/index.php/free/58-convert-ip-address-to-number

+10
source

Here's a simple implementation that outputs what you requested:

 public static void main(String args[]) { String start = "192.168.0.2"; String end = "192.168.0.254"; String[] startParts = start.split("(?<=\\.)(?!.*\\.)"); String[] endParts = end.split("(?<=\\.)(?!.*\\.)"); int first = Integer.parseInt(startParts[1]); int last = Integer.parseInt(endParts[1]); for (int i = first; i <= last; i++) { System.out.println(startParts[0] + i); } } 

Please note that this will only work for ranges containing the last part of the IP address.

+3
source

Start with 2, count to 254 and set to “192.168.0”. in front of him:

 for (int i = 2; i <= 254; i++) { System.out.println("192.168.0." + i); } 
+2
source
 void main(String args[]) { String start = "192.168.0.2"; String end = "192.168.0.254"; String[] startParts = start.split("(?<=\\.)(?!.*\\.)"); String[] endParts = end.split("(?<=\\.)(?!.*\\.)"); int first = Integer.parseInt(startParts[1]); int last = Integer.parseInt(endParts[1]); for (int i = first; i <= last; i++) { System.out.println(startParts[0] + i); } } 
+1
source

Source: https://habr.com/ru/post/896615/


All Articles