日期:2014-05-17 浏览次数:20822 次
C# codestatic List<string> openPort=new List<string>(); string scanPort=""; static void Main(string[] args) { Scan(ip, startPort, endPort); //端口扫描 for(int i=0;i<openPort.Count;i++) { scanPort++; } } static void Scan(IPAddress ip, int startPort, int endPort) { Random rand = new Random((int)DateTime.Now.Ticks); Console.WriteLine("Begin Scan..."); 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 { //绑定失败 } } while (true); try { scanSocket.BeginConnect(new IPEndPoint(ip, port), ScanCallBack, new ArrayList() { scanSocket, port}); } catch { continue; } } Console.WriteLine("Port Scan Completed!"); } /// <summary> /// BeginConnect的回调函数 /// </summary> /// <param name="result">异步Connect的结果</param> 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) { openPort.Add("port {0,5}\tOpen.", port); } else { openPort.Add("port {0,5}\tClosed.", port); } //关闭套接字 scanSocket.Close(); }