class1.cs

来自「c#精彩编程百例(源代码)」· CS 代码 · 共 84 行

CS
84
字号
namespace Portscanner
{
    using System;
    using System.Net.Sockets;
    using System.Threading;
    /// <summary>
    ///    Summary description for Class1.
    /// </summary>
    public class PortScan {
    public int port;
    public string Addr;
    public bool[] done = new bool[65536];
    public void Scan() {
        int ret = -1;
        int portnow = port;
        done[portnow] = false;
        TCPClient objTCP = new TCPClient();
        try {
            objTCP.Connect(Addr, portnow);
            Console.WriteLine("Port " + portnow.ToString() + " is open!");
            objTCP.Close();
        }
        catch(SocketException e) {
        }
        done[portnow] = true;
    }
};
    public class Class1
    {
        public Class1()
        {
            //
            // TODO: Add Constructor Logic here
            //

        }
       public static int Main(string[] args)
        {
            //
            // TODO: Add code to start application here
            //
	     Console.WriteLine("PortScanner v0.1");
         Console.WriteLine();
        if (args.Length == 3) {
            int start = Convert.ToInt32(args[1]);
            int end = Convert.ToInt32(args[2]);
            if ((start >= 0 && start <= 65536) && (end >= 0 && end <= 65536)) {
                int i;
                bool done = true;
                Console.WriteLine("Starting scan... (this may take a few minutes)");
                PortScan objPortscan = new PortScan();
                objPortscan.Addr = args[0];
                for (i=start; i<=end; i++) {
                    objPortscan.port = i;
                    Thread scanThread = new Thread(new ThreadStart(objPortscan.Scan));
                    scanThread.Start();
                    System.Threading.Thread.Sleep(100);
                }
                //wait for all the threads to finish before terminating application
                while (!done) {
                    done = true;
                    for (i=start; i<=end; i++) {
                        if (!objPortscan.done[i]) {
                            done = false;
                        }
                    }
                    System.Threading.Thread.Sleep(1000);
                }
                Console.WriteLine("Scan complete.");
            } else {
                Console.WriteLine("start/end scan range is out of range [0-65536]");
            }
        } else {
            Console.WriteLine("Usage: portscanner host startport endport");
            Console.WriteLine();
            Console.WriteLine("host      - IP/hostname of machine to scan");
            Console.WriteLine("startport - port number to start scan from [0-65536]");
            Console.WriteLine("endport   - port number to end scan on [0-65536]");
        }
        return 0;
        }
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?