简体   繁体   中英

c# Ping a TCP Client from the server

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 a List 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;
}

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM