package test;
import java.io.IOException;
import java.net.*;
import java.util.Enumeration;
public class GetLocalHost {
public static void main(String[] args) throws Exception {
int inputPort = 8400;
System.out.println("输入端口:" + inputPort + ", 递增递归找到可用端口为:" + getUsablePort(inputPort));
}
/**
* 根据输入端口号,递增递归查询可使用端口
* @param port 端口号
* @return 如果被占用,递归;否则返回可使用port
*/
public static int getUsablePort(int port) throws IOException {
boolean flag = false;
Socket socket = null;
InetAddress theAddress = InetAddress.getByName("127.0.0.1");
try{
socket = new Socket(theAddress, port);
flag = true;
} catch (IOException e) {
//如果测试端口号没有被占用,那么会抛出异常,通过下文flag来返回可用端口
} finally {
if(socket!=null) {
//new了socket最好释放
socket.close();
}
}
if (flag) {
//端口被占用,port + 1递归
port = port + 1;
return getUsablePort(port);
} else {
//可用端口
return port;
}
}
}
与实际相符,则正确
lsof -i:[端口号]
kill 3187244