【c#】【分享】c#扫描器
Page 1 of 1
【c#】【分享】c#扫描器
XScanner,SuperScanner,小榕的流光。。。大家都听过并且玩过吧?在这里我发一个实现这种端口扫描器的demo,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
openedPorts = new List (); - //起始扫描端口
- static int startPort = 1;
- //结束端口号
- static int endPort = 500;
- //最大工作线程数
- static int maxThread = 100;
- static void Main(string[] args)
- {
- //接收传入参数一作为要扫描的主机
- string host = args[0];
- //接收传入参数二作为端口扫描范围,如1-4000
- string portRange = args[1];
- 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));
- [You must be registered and logged in to see this link.]
- }
- finally
- {
- tc.Close();
- tc = null;
- Program.scannedCount++;
- Program.runningThreadCount--;
- [You must be registered and logged in to see this link.]
- }
- }
- }
- }
cyjian- Spammer
- Posts : 211
Points : 72995
Reputation : 0
Join date : 2014-06-18
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum
|
|