Determine if the server is listening on this port.

I need to interrogate a server running some proprietary software to determine if this service is running. Using wirehark, I was able to narrow down the TCP port used, but it seems that the traffic is encrypted.

In my case, its safe bet is that if the server accepts connections (i.e. telnet serverName 1234), the service ends and everything is in order. In other words, I don't need any actual data exchange, just open the connection and then calmly close it.

I am wondering how I can emulate this using C # and Sockets. My network programming mostly ends with WebClient, so any help here is much appreciated.

+3
source share
4 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) 
        {
            // ...
        }
    }
}
+6
source

Just use TcpClienttry 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;
    }
}
+3
source

. ... , , .NET.

- , . , , . ...

public static bool IsServerUp(string server, int port, int timeout)
    {
        bool isUp;

        try
        {
            using (TcpClient tcp = new TcpClient())
            {
                IAsyncResult ar = tcp.BeginConnect(server, port, null, null);
                WaitHandle wh = ar.AsyncWaitHandle;

                try
                {
                    if (!wh.WaitOne(TimeSpan.FromMilliseconds(timeout), false))
                    {
                        tcp.EndConnect(ar);
                        tcp.Close();
                        throw new SocketException();
                    }

                    isUp = true;
                    tcp.EndConnect(ar);
                }
                finally
                {
                    wh.Close();
                }
            } 
        }
        catch (SocketException e)
        {
            LOGGER.Warn(string.Format("TCP connection to server {0} failed.", server), e);
            isUp = false;
        }

        return isUp;
+2

TcpClient .

0

Source: https://habr.com/ru/post/1745496/


All Articles