日期:2014-05-17  浏览次数:20934 次

端口扫描取值问题
我想把打开的端口,跟关闭的端口,结果放到两个list中去,求大牛们帮帮忙

C# code

static void Main(string[] args)  
        {  
           
           
            Scan(ip, startPort, endPort);   //端口扫描   
              
             
        }  

 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)  
            {  
              
                Console.WriteLine("port {0,5}\tOpen.", port);  
            }  
            else  
            {  
                 Console.WriteLine("port {0,5}\tClose.", port);  
            }  
            //关闭套接字   
            scanSocket.Close();  
        }  





------解决方案--------------------
群友帮顶 希望给出的解决方案是你需要的