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

Enable Visual Studio to use more than 2GB of memory

Firefox and Chrome dark mode

Dealing with the morons who built Dell 7710 and RAID