我将如何添加一个循环来计算当前打开端口的数量?

How would I add a loop that counts the current number of open ports?

此程序扫描我的本地计算机并找到所有打开的端口。它 returns 找到打开的端口并打印显示该端口的语句。我需要添加一个计数器循环来主动计算当前打开端口的数量。我的代码如下:

public class LowPortScanner {

  public static void main(String[] args) {
    final int maxPort = 1024;   // It takes forever to scan all 65536 ports
    String host = "localhost";

    System.err.println("This is an error message");

    if (args.length > 0) {
      host = args[0];
    }
    System.out.println("Scanning ports on " + host + "...");
    for (int i = 1; i <= maxPort; i++) {
      try {
        Socket s = new Socket(host, i);
        // If we get this far, we were able to open the socket. Someone is listening
        System.out.println("There is a something listening on port " + i + " of " + host);
        // Now close it because all we cared about was trying to open it..
        s.close();
      }
      catch (UnknownHostException ex) {
        System.err.println(ex);
        break;
      }
      catch (IOException ex) {
        // There must not be a server on this port
        // We will eat this exception because it will happen too many times.
      }
    }   // end for  
    int portCount = 0;
    for (int i = 0; portCount > 0; i++) {
        portCount = i + portCount;
        System.out.println("There are currently " + i + " ports open");
    }
  }  // end main
}  // end PortScanner

我正在处理的计数器是

    int portCount = 0;
    for (int i = 0; portCount > 0; i++) {
        portCount = i + portCount;
        System.out.println("There are currently " + i + " ports open");
    }

你必须计算打开的端口,你现在写的循环不会做任何有用的事情。

您应该在要检查所有端口的循环之前初始化计数器。

然后当端口打开时(打印端口打开的地方)将计数器加 1。循环完成后,您可以打印具有打开端口总数的计数器。

看起来像这样。

public class LowPortScanner {

  public static void main(String[] args) {
    final int maxPort = 1024;   // It takes forever to scan all 65536 ports
    String host = "localhost";

    System.err.println("This is an error message");

    if (args.length > 0) {
      host = args[0];
    }
    int portCount = 0; //initialize the counter
    System.out.println("Scanning ports on " + host + "...");
    for (int i = 1; i <= maxPort; i++) {
      try {
        Socket s = new Socket(host, i);
        // If we get this far, we were able to open the socket. Someone is listening
        System.out.println("There is a something listening on port " + i + " of " + host);
        // Now close it because all we cared about was trying to open it..
        portCount++; //port is open so increase counter
        s.close();
      }
      catch (UnknownHostException ex) {
        System.err.println(ex);
        break;
      }
      catch (IOException ex) {
        // There must not be a server on this port
        // We will eat this exception because it will happen too many times.
      }
    }   // end for  
    //print amount of open ports
    System.out.println("There are currently " + portCount + " ports open");

  }  // end main
}  // end PortScanner