c sharp学习第一天,简单端口扫描器

作者: admin 分类: 未分类 发布时间: 2016-12-17 17:26

代码来源:http://blog.csdn.net/xiaohui_hubei/article/details/7515103

c sharp学习第一天,简单端口扫描器

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Collections;
namespace portscan
{
class Program
{
static void Main(string[] args)
{
IPAddress ip;
int startPort, endPort;
if (GetPortRange(args,out ip, out startPort, out endPort) == true) {
scan(ip, startPort, endPort);
}

}
private static bool GetPortRange(string[] args,out IPAddress ip,out int startPort,out int endPort) {
ip = null;
startPort = endPort = 0;
if(args.Length !=0 && (args[0] == “/?”||args[0]==”/help”)){
help();
return false;

}
if (args.Length == 3)
{
if (IPAddress.TryParse(args[0], out ip) && int.TryParse(args[1], out startPort) && int.TryParse(args[2], out endPort))
{
return true;
}
else
{
help();
return false;

}
}
else {
help();
return false;

}

}
static void scan(IPAddress ip,int startPort,int endPort) {
Random rand = new Random((int)DateTime.Now.Ticks);
Console.WriteLine(“Begin Scan…”);
Console.WriteLine(“Scaning {0}”, ip);

for (int port = startPort; port < endPort; port++) { Socket scansocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.IP); do{ try{ scansocket.Bind(new IPEndPoint(IPAddress.Any,rand.Next(65535))); break; }catch{ // Console.WriteLine("Bind fail!"); } }while(true); try { scansocket.BeginConnect(new IPEndPoint(ip, port), ScanCallBack, new ArrayList() { scansocket,port}); } catch { continue; } } Console.WriteLine("\nPort Scan Completed!"); } static void ScanCallBack(IAsyncResult result) { ArrayList arrList = (ArrayList)result.AsyncState; Socket scanSocket = (Socket)arrList[0]; int port = (int)arrList[1]; if (result.IsCompleted && scanSocket.Connected) { Console.WriteLine("port {0,5}\tOpen.", port); } else { // Console.WriteLine("port {0,5}\tCloseed.", port); } scanSocket.Close(); } static void help() { Console.WriteLine("Scan port from startPort to endPort of the host specified by the IPAddress."); Console.WriteLine("Command Format:"); Console.WriteLine("PortScan IPAddress startPort endPort"); Console.WriteLine("For example:"); Console.WriteLine("portscan 127.0.0.1 80 8080"); } } } [/csharp]

标签云