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(); //输出结果 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); } } } }