/// <summary>
    /// Port Scan 2013-01-30 00:36:00
    /// </summary>
    class Program
    {
        static string ipAddress;
        static int runningThread = 0;
        static List<string> portOpen = new List<string>();
        static void Main(string[] args)
        {
            int portSta;
            int portSto;
            int maxThread = 100;
            Console.WriteLine("PortScan");
            Console.Write("IP地址:");
            ipAddress = Console.ReadLine();
            if (!Regex.IsMatch(ipAddress, @"^(?!0{1,3}\.)(?:[01]?\d{0,2}|2[0-4]\d|25[0-5])\.(?:[01]?\d{0,2}|2[0-4]\d|25[0-5])\.(?:[01]?\d{0,2}|2[0-4]\d|25[0-5])\.(?:[01]?\d{0,2}|2[0-4]\d|25[0-5])$")) return;
            Console.Write("起始端口:");
            portSta = int.Parse(Console.ReadLine());
            Console.Write("结束端口:");
            portSto = int.Parse(Console.ReadLine()) + 1;
            Console.Write("线程数量:");
            maxThread = int.Parse(Console.ReadLine());
            List<Thread> tArr = new List<Thread>();
            for (int i = portSta; i < portSto; i++)
            {
                Thread thread = new Thread(new ParameterizedThreadStart(AppScan));
                thread.Start(i.ToString());
                runningThread++;
                tArr.Add(thread);
                while (maxThread <= runningThread) ;
            }
            foreach (Thread t in tArr)
            {
                t.Join();
            }
            Console.WriteLine("// ----------- Open Port");
            foreach (string port in portOpen)
            {
                Console.WriteLine("   {0} Is Open", port);
                File.AppendAllText("portScan.ini", port + " Is Open" + System.Environment.NewLine);
            }
            Console.WriteLine("// ----------- Finished ");
        }
        static void AppScan(object o)
        {
            string portStr = o.ToString().PadLeft(5, ' ');
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(ipAddress), int.Parse(o.ToString()));
            Socket socket = new Socket(ipep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                socket.Connect(ipep);
                portOpen.Add(portStr.Trim(' '));
                Console.WriteLine("{0} : Open", portStr);
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0} : Closed -> {1}", portStr, ex.Message);
            }
            finally { }
            runningThread--;
        }
    }