1. 程式人生 > >網路程式設計-Socket類埠掃描器

網路程式設計-Socket類埠掃描器

客戶端套接字
埠掃描器JPortScanner.java
import java.net.*;
import java.io.*;

//埠掃描
public class JPortScanner {
  private String host;  //目標主機
  private int fromPort; //起始埠
  private int toPort;   //結束埠
	
  public JPortScanner(String host, int fromPort, int toPort) {
    this.host = host;
    this.fromPort = fromPort;
    this.toPort = toPort;
  }

  public JPortScanner(String host) {
    this(host, 1, 1023); //預設埠範圍: 1-1023
  }
	
  public void start() {
    Socket connect = null;

    for(int port=this.fromPort; port<=this.toPort; port++) {
      try {
        connect = new Socket(host, port);
        System.out.println("開放埠: " + port);
      }
      catch(UnknownHostException e) {
        System.err.println("無法識別主機: " + host);
        break;
      }
      catch(IOException e) {
        System.out.println("未響應埠: " + port);
      }
      finally {
        try {
          connect.close();
        }catch(Exception e) {}
      }
    }
  }
	
  public static void main(String[] args) {
    if(args.length == 1) {//命令列引數指定主機
      (new JPortScanner(args[0])).start();
    }
    else if(args.length == 3) {//命令列引數指定主機、起始埠和結束埠
      (new JPortScanner(args[0], 
        Integer.parseInt(args[1]),Integer.parseInt(args[2]))).start();
    }
    else { //命令格式
      System.out.println("Usage:java JPortScanner [FromPort] [ToPort]");
    }
  }
}

擴充套件:
1、常用埠號?