Check if something is listening at a port on a server using C#

IPAddress [] hostIPAddresses = Dns.GetHostAddresses(hostName);
            IPAddress selectedIPAddress = null;

            if (hostIPAddresses == null || hostIPAddresses.Length == 0) { return ListenerStatus.Unknown; }

            for (int i = 0; i < hostIPAddresses.Length; i++)
            {
                if (hostIPAddresses[i].AddressFamily == AddressFamily.InterNetwork)
                {
                    selectedIPAddress = hostIPAddresses[i];
                    break;
                }
            }

            if (selectedIPAddress == null) { return ListenerStatus.Unknown; }

            Socket socketInstance = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                socketInstance.Connect(selectedIPAddress, port);

                if (socketInstance.Connected == true)
                {
                    //Port is in use and connection is successful          
                    return ListenerStatus.Listening;
                }

                return ListenerStatus.NotListening;
            }
            catch (SocketException ex)
            {
                if (ex.ErrorCode == 10061)
                {
                    //Port is unused and could not establish connection        
                    return ListenerStatus.NotListening;
                }

                return ListenerStatus.Unknown;
            }
            finally
            {
                if (socketInstance != null)
                {
                    socketInstance.Close();
                }
            }

Comments

Popular posts from this blog

Tutorial: Using Google Cloud Storage from C# and .NET

Late 2008 Macbook only giving 1.5 gb/s speed with 6 gb/s Intel SSD?

Enable Visual Studio to use more than 2GB of memory