4

How can a TcpClient be pinged from a server in order to see its response time? I have a TCPServer that I have created with a TCPClientManager that I have also created. This simply adds a new Client with a .NET TcpClient property to aList whenever a client connects. How can I get the address of the TcpClient so that I can ping it using .NET Ping ?

public long PingClient(Client client)
{
    long pingTime = 0;
    Ping pingSender = new Ping();

    // The class Client has a property tcpClient of type TcpClient
    IPAddress address = IPAddress.Parse(Client.tcpClient...???);
    PingReply reply = pingSender.Send(address);

    if (reply.Status == IPStatus.Success)
    {
        pingTime = reply.RoundtripTime;
    }

    return pingTime;
}
Markus Safar
  • 6,324
  • 5
  • 28
  • 44
user3822370
  • 641
  • 7
  • 20
  • Possible duplicate of [How do I get client ip address using TcpClient?](http://stackoverflow.com/questions/2717381/how-do-i-get-client-ip-address-using-tcpclient) – cbr Nov 28 '15 at 19:59

1 Answers1

4

If I understood your question correctly you want the IPAddress of the connected TcpClient which can be accomplished by accessing the underlaying socket (which is exposed through the Client property) and using it's EndPoint property.

You will have to cast it to an IPEndPoint in order to access it correctly.

In your case just use ((IPEndPoint)client.Client.RemoteEndPoint).Address which will return an IPAddress.

So you would have to change your example from:

IPAddress address = IPAddress.Parse(Client.tcpClient...???);

to:

IPAddress address = ((IPEndPoint)client.Client.RemoteEndPoint).Address;
Markus Safar
  • 6,324
  • 5
  • 28
  • 44