public class PortScannerSingleThread { public static void main(String[] args) { String host = null; //第一个参数,目标主机。 int beginport = 1; //第二个参数,开始端口。 int endport = 65535; //第三个参数,结束端口。 try{ host = args[0]; beginport = Integer.parseInt(args[1]); endport = Integer.parseInt(args[2]); if(beginport <= 0 || endport >= 65536 || beginport > endport){ throw new Exception("Port is illegal"); } }catch(Exception e){ System.out.println("Usage: java PortScannerSingleThread host beginport endport"); System.exit(0); }
for (int i = beginport; i <= endport; i++) { try { Socket s = new Socket(host, i); System.out.println("The port " + i + " is opened at " + host); }catch (UnknownHostException ex) { System.err.println(ex); break; }catch (IOException ex) { } } } } -------------------------------------------------------------------------------------------------------- 在以上程序中,通过java.net.Socket类来识别端口是否是open状态。程序接受3个参数,第一个参数是主机IP,第二和第三个参数是需要扫描的起始和中止的端口号(1~65535)。本程序(java PortScannerSingleThread 10.1.1.1 1 1000)运行结果如下: The port 25 is opened at 10.1.1.182 The port 110 is opened at 10.1.1.182 The port 135 is opened at 10.1.1.182 ...
public void run(){ try{ Socket s = new Socket(host,port); System.out.println("The port " + port + " is opened at " + host); }catch(UnknownHostException ex){ System.err.println(ex); }catch(IOException ioe){ } } }