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

端口异步扫描问题
问题描述,加断点调试,openPort有值,但直接运行openPort就为空了。这是怎么回事啊
C# code
static 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();  
        }  



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

嘿嘿 挺好 给一个解决方案 得三个问题积分

谢谢LZ