当前位置:文档之家› c#端口扫描器

c#端口扫描器


using System;
using System.Collections.Generic;
using System.Text;

using https://www.doczj.com/doc/a88042407.html,;
using https://www.doczj.com/doc/a88042407.html,.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));
https://www.doczj.com/doc/a88042407.html, = 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 (https://www.doczj.com/doc/a88042407.html,.Sockets.SocketException e)
{
//容错处理
Console.WriteLine("Port {0} is close

d", m_port.ToString().PadRight(6));
//Console.WriteLine(e.Message);
}
finally
{
tc.Close();
tc = null;
Program.scannedCount++;
Program.runningThreadCount--;

//Console.WriteLine(Program.scannedCount);

}
}
}
}



相关主题
文本预览
相关文档 最新文档