Java如何檢查埠是否被使用?

2019-10-16 22:28:09

在Java程式設計中,如何掃描開啟的埠(是否被使用)?

以下範例顯示如何通過建立 Socket 物件來檢查主機上開啟或正在使用的埠(相當於一個簡單的埠掃描器)。

package com.yiibai;

import java.net.*;
import java.io.*;

public class CheckPort {
    public static void main(String[] args) {
        Socket Skt;
        String host = "localhost";

        if (args.length > 0) {
            host = args[0];
        }
        for (int i = 100; i < 1024; i++) {
            try {
                System.out.println("Looking for " + i);
                Skt = new Socket(host, i);
                System.out.println("There is a server on port " + i + " of " + host);
            } catch (UnknownHostException e) {
                System.out.println("Exception occured" + e);
                break;
            } catch (IOException e) {
            }
        }
    }
}

上述程式碼範例將產生以下結果 -

......
Looking for 133
Looking for 134
Looking for 135
There is a server on port 135 of localhost
Looking for 136
Looking for 137
Looking for 138
......