查找服務器可用端口號

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.UnknownHostException;

/**
 * @author N3verL4nd
 * @date 2020/4/14
 */
public class NetUtil {
    public static final String ANYHOST = "0.0.0.0";
    public static final int MAX_PORT = 20000;
    public static final int MIN_PORT = 1025;

    public static int getAvailablePort(int defaultPort) {
        int port = defaultPort;
        while (port < MAX_PORT) {
            if (!isPortInUse(port)) {
                return port;
            } else {
                port++;
            }
        }
        while (port > MIN_PORT) {
            if (!isPortInUse(port)) {
                return port;
            } else {
                port--;
            }
        }
        throw new IllegalStateException("No available port");
    }

    public static String toIpPort(InetSocketAddress socketAddress) {
        StringBuilder localIpPort = new StringBuilder();
        if (socketAddress != null) {
            InetAddress address = socketAddress.getAddress();
            if (address != null && address.getHostAddress() != null) {
                localIpPort.append(address.getHostAddress());
            }
            localIpPort.append(":").append(socketAddress.getPort());
        }
        return localIpPort.toString();
    }

    private static boolean isPortInUse(int port) {
        try {
            bindPort(ANYHOST, port);
            bindPort(InetAddress.getLocalHost().getHostAddress(), port);
            return false;
        } catch (Exception e) {
            return true;
        }
    }

    private static void bindPort(String host, int port) throws IOException {
        ServerSocket s = new ServerSocket();
        s.bind(new InetSocketAddress(host, port));
        s.close();
    }

    public static void main(String[] args) throws UnknownHostException {
        System.out.println(InetAddress.getLocalHost());
        System.out.println(InetAddress.getLocalHost().getHostAddress());
        System.out.println(toIpPort(new InetSocketAddress("127.0.0.1", 8080)));
    }
}

在服務器中,0.0.0.0指的是本機上的所有IPV4地址,如果一個主機有兩個IP地址,192.168.1.1 和 10.1.2.1,並且該主機上的一個服務監聽的地址是0.0.0.0,那麼通過兩個ip地址都能夠訪問該服務。

動態端口的範圍是從1024~65535,1024端口一般不固定分配給某個服務,在英文中的解釋是“Reserved”(保留)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章