Java 示例 - 检查端口

  • 问题描述

    如何检查端口是否正在使用?
  • 解决方案

    以下示例显示了如何通过创建套接字对象来检查是否有任何端口被用作服务器。
    
    import java.net.*;
    import java.io.*;
    public class Main {
       public static void main(String[] args) {
          Socket Skt;
          String host = "localhost";
          
          if (args.length > 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. . .