Check If A Port Is Open Or Closed

			
                            using System.Net.Sockets;
                            
                            string hostname = "localhost";
                            int portno = 2100;
                            IPAddress ipa = (IPAddress) Dns.GetHostAddresses(hostname)[0];
                            try
                            {
                                Socket sock = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
                                sock.Connect(ipa, portno);
                                if (sock.Connected == true) // Port is in use and connection is successful
                                MessageBox.Show("Port is Closed");
                                sock.Close();
                            }
                            catch (System.Net.Sockets.SocketException ex)
                            {
                                if (ex.ErrorCode == 10061) // Port is unused or could not establish connection
                                MessageBox.Show("Port is Open!");
                                else
                                MessageBox.Show(ex.Message);
                            }