views:

80

answers:

3

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.

A: 

Use the TcpClient class to connect the server.

compie
+1  A: 

Just use TcpClient try to connect to the server, TcpClient.Connect will throw an exception if the connection fails.

bool IsListening(string server, int port)
{
    using(TcpClient client = new TcpClient())
    {
        try
        {
            client.Connect(server, port);
        }
        catch(SocketException)
        {
            return false;
        }
        client.Close();
        return true;
    }
}
Phil Lamb
Is there a way to adjust the connect timeout? It seems to fail, but only after about a minute...
Nate Bross
+1  A: 

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) 
        {
            // ...
        }
    }
}
ChaosPandion
Is there a way to adjust the connect timeout? It seems to fail, but only after about a minute...
Nate Bross
@Nate I believe that is how long the process takes. There is no connection timeout option.
ChaosPandion
I added `if(ex.SocketErrorCode == SocketError.ConnectionRefused || ex.SocketErrorCode == SocketError.TimedOut)`
Nate Bross