简体   繁体   English

c#从服务器ping一个TCP客户端

[英]c# Ping a TCP Client from the server

How can a TcpClient be pinged from a server in order to see its response time? 如何从服务器ping通TcpClient以查看其响应时间? I have a TCPServer that I have created with a TCPClientManager that I have also created. 我有一个TCPServer ,我用我创建的TCPClientManager创建。 This simply adds a new Client with a .NET TcpClient property to a List whenever a client connects. 只要客户端连接,这只是将一个带有.NET TcpClient属性的新Client添加到List How can I get the address of the TcpClient so that I can ping it using .NET Ping ? 如何获取TcpClient的地址以便我可以使用.NET Ping对其进行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. 如果我正确理解了您的问题,您需要连接的TcpClientIPAddress ,这可以通过访问底层套接字(通过Client属性公开)并使用它的EndPoint属性来完成。

You will have to cast it to an IPEndPoint in order to access it correctly. 您必须将其IPEndPoint转换为IPEndPoint才能正确访问它。

In your case just use ((IPEndPoint)client.Client.RemoteEndPoint).Address which will return an IPAddress . 在您的情况下,只需使用((IPEndPoint)client.Client.RemoteEndPoint).Address将返回IPAddress

So you would have to change your example from: 所以你必须改变你的例子:

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

to: 至:

IPAddress address = ((IPEndPoint)client.Client.RemoteEndPoint).Address;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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