指定ipのポートをスキャン(C#)

6607 ワード

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

        }

    }