Java檢查端口占用
Java如何檢查端口是否被使用?
解決方法
下麵的示例演示如何通過創建一個套接字對象檢查端口是否被服務器使用。
import java.net.*; import java.io.*; public class Main { public static void main(String[] args) { Socket Skt; String host = "localhost"; if (args.length gt; 0) { host = args[0]; } for (int i = 0; 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 0 Looking for 1 Looking for 2 Looking for 3 Looking for 4. . .