Search code examples
javaloopswhile-loopinfinite-loopinetaddress

Loop continuously between a specified range java


I am making a Java application that will loop through my DHCP table and attempt connection to multiple devices. I am looping through an IP range, but would like to continuously loop through the range until the application is closed. What would be the best practice in for continuously looping? set the value for the startiptwice, then set the startip back to the original once the maximum range is reached? Below is what I currently have:

public void loopFTP(String startIP, String endIP, int timeout) throws SocketException, IOException {
    InetAddress startAsIP = InetAddresses.forString(startIP);
    InetAddress endAsIP = InetAddresses.forString(endIP);
    while(InetAddresses.coerceToInteger(startAsIP) <= InetAddresses.coerceToInteger(endAsIP)){
        System.out.println(startAsIP);
        attemptConnection(startAsIP, timeout);
        startAsIP = InetAddresses.increment(startAsIP);

    }
}

Solution

  • If your loop should be infinite, you could use a for(;;) or a while(true) loop.

    When the end of the range is reached, just reset startAsIP based on the startIP value :

    public void loopFTP(String startIP, String endIP, int timeout) throws SocketException, IOException {
        InetAddress startAsIP = InetAddresses.forString(startIP);
        InetAddress endAsIP = InetAddresses.forString(endIP);
        while(true){
    
            System.out.println(startAsIP);
            attemptConnection(startAsIP, timeout);
    
            if(InetAddresses.coerceToInteger(startAsIP) <= InetAddresses.coerceToInteger(endAsIP))
                startAsIP = InetAddresses.increment(startAsIP);
            else
                startAsIP = InetAddresses.forString(startIP);
    
    
        }
    }