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

一段扫描端口的代码,希望高人帮我改一个小bug
问题描述,加断点调试,openPort有值,但直接运行openPort就为空了。这是怎么回事啊
C# code


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();  
        }  





------解决方案--------------------
带Main(string[] args)参数的用vs直接启动是取不到值。编译成exe然后在控制台里运行并输入参数。