上网很久的朋友一定对端口扫描器不会陌生吧。XScanner,SuperScanner大家一定都使用过。
今天我们就用最新的.Net技术来制作一个自己的端口扫描器!
今天主要使用到的是System.Net和System.Threading名称空间.
(本文来源于图老师网站,更多请访问http://m.tulaoshi.com/bianchengyuyan/)12using System;3using System.Collections.Generic;4using System.Text;56using System.Net;7using System.Net.Sockets;89using System.Threading;1011namespace PortScanner12{13 class Program14 {15 //已扫描端口数目16 internal static int scannedCount = 0;17 //正在运行的线程数目18 internal static int runningThreadCount = 0;19 //打开的端口数目20 internal static Listint openedPorts = new Listint();21 //起始扫描端口22 static int startPort = 1;23 //结束端口号24 static int endPort = 500;25 //最大工作线程数26 static int maxThread = 100;27 static void Main(string[] args)28 {29 //接收传入参数一作为要扫描的主机30 string host = args[0];31 //接收传入参数二作为端口扫描范围,如1-400032 string portRange = args[1];33 startPort = int.Parse(portRange.Split('-')[0].Trim());34 endPort = int.Parse(portRange.Split('-')[1].Trim());3536 for (int port = startPort; port endPort; port++)37 {38 //创建扫描类39 Scanner scanner = new Scanner(host, port);40 Thread thread = new Thread(new ThreadStart(scanner.Scan));41 thread.Name = port.ToString();42 thread.IsBackground = true;43 //启动扫描线程44 thread.Start();4546 runningThreadCount++;4748 Thread.Sleep(10);49 //循环,直到某个线程工作完毕才启动另一新线程,也可以叫做推拉窗技术50 while (runningThreadCount = maxThread) ;51 }5253 //空循环,直到所有端口扫描完毕54 while (scannedCount + 1 (endPort - startPort)) ;5556 Console.WriteLine();57 Console.WriteLine();58 //输出结果59 Console.WriteLine("Scan for host: {0} has been completed ,total {1} ports scanned,opened ports :{2}",60 host, (endPort - startPort), openedPorts.Count);6162 foreach (int port in openedPorts)63 Console.WriteLine(" Port: {0} is open", port.ToString().PadLeft(6));64 }65 }6667 //扫描类68 class Scanner69 {70 string m_host;71 int m_port;72 73 public Scanner(string host, int port)74 {75 m_host = host; m_port = port;76 }7778 public void Scan()79 {80 //我们直接使用比较高级的TcpClient类81 TcpClient tc = new TcpClient();82 //设置超时时间83 tc.SendTimeout = tc.ReceiveTimeout = 2000;84 try85 {86 //Console.Write("Checking port: {0}", m_port);87 //尝试连接88 tc.Connect(m_host, m_port);89 if (tc.Connected)90 {91 //如果连接上,证明此商品为开放状态92 Console.WriteLine("Port {0} is Open", m_port.ToString().PadRight(6));93 Program.openedPorts.Add(m_port);94 }95 }96 catch (System.Net.Sockets.SocketException e)97 {98 //容错处理99 Console.WriteLine("Port {0} is closed", m_port.ToString().PadRight(6));100 //Console.WriteLine(e.Message);101 }102 finally103 {104 tc.Close();105 tc = null;106 Program.scannedCount++;107 Program.runningThreadCount--;108109 //Console.WriteLine(Program.scannedCount);110 111 }112 }113 }114}115116117
好了,代码很简单吧!只能扫描TCP端口哦。
(本文来源于图老师网站,更多请访问http://m.tulaoshi.com/bianchengyuyan/)