判断端口占用
1 public static boolean isPortUsing(String host,int port) throws IOException { 2 boolean flag = false; 3 InetAddress theAddress = InetAddress.getByName(host); 4 Socket socket=null; 5 try { 6 socket = new Socket(theAddress,port); 7 flag = true; 8 logger.info(String.format("%s:%d可以连接.",host,port)); 9 } catch (IOException ignored) { 10 11 } finally { 12 if(socket!=null && socket.isConnected()){ 13 socket.close(); 14 } 15 } 16 return flag; 17 }
new Socket操作后只是对目标端口进行了监听,并非去使用目标端口;所以如果可以正常创建Socket,则可以证明主机上的目标端口已经被使用(并非此Socket使用的);反之则证明这个端口并没有程序使用

浙公网安备 33010602011771号