天天看點

C#掃描計算機端口

using system;

using system.collections.generic;

using system.text;

using system.net;

using system.net.sockets;

using system.threading;

namespace portscanner

{

class program

 //已掃描端口數目

 internal static int scannedcount = 0;

 //正在運作的線程數目

 internal static int runningthreadcount = 0;

 //打開的端口數目

 internal static list<int> openedports = new list<int>();

 //起始掃描端口

 static int startport = 1;

 //結束端口号

 static int endport = 500;

 //最大工作線程數

 static int maxthread = 10;

 static void main(string[] args)

 {

  //接收傳入參數一作為要掃描的主機

  string host = "192.168.0.1";

  //接收傳入參數二作為端口掃描範圍,如1-4000

  string portrange = "1-400";

  startport = int.parse(portrange.split('-')[0].trim());

  endport = int.parse(portrange.split('-')[1].trim());

  for (int port = startport; port < endport; port++)

  {

   //建立掃描類

   scanner scanner = new scanner(host, port);

   thread thread = new thread(new threadstart(scanner.scan));

   thread.name = port.tostring();

    thread.isbackground = true;

   //啟動掃描線程

   thread.start();

   runningthreadcount++;

   thread.sleep(10);

   //循環,直到某個線程工作完畢才啟動另一新線程,也可以叫做推拉窗技術

   while (runningthreadcount >= maxthread) ;

  }

  //空循環,直到所有端口掃描完畢

  while (scannedcount + 1 < (endport - startport)) ;

   console.writeline();

   //輸出結果

   console.writeline("scan for host: {0} has been completed , /n total {1} ports scanned, /nopened ports :{2}",

host, (endport - startport), openedports.count);

  foreach (int port in openedports)

   console.writeline("/tport: {0} is open", port.tostring().padleft(6));

 }

}

//掃描類

class scanner

 string m_host;

 int m_port;

 

 public scanner(string host, int port)

  m_host = host; m_port = port;

 public void scan()

  //我們直接使用比較進階的tcpclient類

  tcpclient tc = new tcpclient();

  //設定逾時時間

  tc.sendtimeout = tc.receivetimeout = 2000;

  try

   //console.write("checking port: {0}", m_port);

   //嘗試連接配接

   tc.connect(m_host, m_port);

   if (tc.connected)

   {

    //如果連接配接上,證明此端口為開放狀态

    console.writeline("port {0} is open", m_port.tostring().padright(6));

    program.openedports.add(m_port);

   }

  catch (system.net.sockets.socketexception e)

   //容錯處理

   console.writeline("port {0} is closed", m_port.tostring().padright(6));

    //console.writeline(e.message);

   }

   finally

   {

    tc.close();

    tc = null;

    program.scannedcount++;

  program.runningthreadcount--;

    //console.writeline(program.scannedcount);

  }