我正在制作一个Java应用程序,该应用程序将通过我的DHCP表循环并尝试连接到多个设备。我正在遍历IP范围,但希望连续循环遍历该范围,直到关闭应用程序。连续循环的最佳做法是什么?两次设置startip
的值,然后在达到最大范围后将startip
设置回原始?以下是我目前拥有的:
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);
}
}
如果您的循环是无限的,则可以使用for(;;)
或while(true)
环路。
到达范围的末端时,只需基于startIP
值重置startAsIP
:
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);
}
}