How do I get generate an IP address range given start and end IP address?

后端 未结 5 452
既然无缘
既然无缘 2020-12-19 06:12

How can generate a range of IP addresses from a start and end IP address?

Example for a network \"192.168.0.0/24\":

String start = \"192.168.0.2\"
S         


        
5条回答
  •  情深已故
    2020-12-19 06:56

    Here's simple implementation that outputs what you asked for:

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

    Note that this will only work for ranges involving the last part of the IP address.

提交回复
热议问题