掃描指定ip的端口(C#)

    class PingExam
    {
        public static void Main()
        {
            Ping ping = new Ping();
            string ip = "192.168.1.43"; // 目標ip
            int[] ports = { 20, 21, 25, 80, 8080, 2588 }; // 須要掃描的端口
            scanPort(IPAddress.Parse(ip), ports);
        }


        private static void scanPort(IPAddress address, int startPort, int endPort)
        {
            int[] ports = new int[endPort - startPort + 1];
            for (int i = 0; i < endPort-startPort+1; i++) {
                ports[i] = startPort + i;
            }
            scanPort(address, ports);
        }


        private static void scanPort(IPAddress address, int[] ports)
        {
            try {
                int count = ports.Length;
                AutoResetEvent[] arEvents = new AutoResetEvent[count]; // 同步對象
                for (int i = 0; i < count; i++) {
                    arEvents[i] = new AutoResetEvent(false); // 同步對象, 初始未觸發
                    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    socket.Bind(new IPEndPoint(IPAddress.Any, 0));
                    socket.BeginConnect(new IPEndPoint(address, ports[i]), 
                        callback, 
                        new ArrayList() { socket, ports[i], arEvents[i]} // 傳遞3個參數: 當前socket, 端口, 同步對象
                        );
                }

                WaitHandle.WaitAll(arEvents); // 等待全部掃描工做完成
            }
            catch (Exception ex) {
                Console.WriteLine(ex.Message);
            }
        }

        private static void callback(IAsyncResult ar) // 掃描完成後的回調方法
        {
            ArrayList list = (ArrayList)ar.AsyncState; // 獲取傳遞的參數
            Socket socket = (Socket)list[0];
            int port = (int)list[1];
            AutoResetEvent arevent = (AutoResetEvent)list[2];

            if (ar.IsCompleted && socket.Connected) {
                Console.WriteLine("port: {0} open.", port); // 檢查 connected屬性, 若是爲true 則表示是開放的
            }
            else {
                Console.WriteLine("port: {0} closed.", port);
            }
            try {
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
            }
            catch {
            }
            arevent.Set(); // 完成後觸發
        }
    }
相關文章
相關標籤/搜索