Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a server is listening on a given port

I need to poll a server, which is running some propriatary software, to determine if this service is running. Using wireshark, I've been able to narrow down the TCP port its using, but it appears that the traffic is encrypted.

In my case, its a safe bet that if the server is accepting connections (i.e. telnet serverName 1234) the service is up and all is OK. In other words, I don't need do any actual data exchange, just open a connection and then safely close it.

I'm wondering how I can emulate this with C# and Sockets. My network programming basically ends with WebClient, so any help here is really appreciated.

like image 612
Nate Avatar asked May 14 '10 18:05

Nate


People also ask

How do I know if my IP is listening on a port?

Enter "telnet + IP address or hostname + port number" (e.g., telnet www.synology.com 1723 or telnet 10.17. xxx. xxx 5000) to run the telnet command and test the port status. If the port is open, a message will say Connected to 10.17.


1 Answers

The process is actually very simple.

using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
    try
    {
        socket.Connect(host, port);
    }
    catch (SocketException ex)
    {
        if (ex.SocketErrorCode == SocketError.ConnectionRefused) 
        {
            // ...
        }
    }
}
like image 108
ChaosPandion Avatar answered Sep 29 '22 14:09

ChaosPandion