c# - 您可以从 System.Net.Sockets.TcpClient 检索主机名和端口吗?

标签 c# networking

是否可以从新的 TcpClient 检索底层主机名/端口?

TcpListener listener = new TcpListener(IPAddress.Any, port);
TcpClient client = listener.AcceptTcpClient();
// get the hostname
// get the port

我在 client.Client(一个 System.Net.Socket)中转了一圈,但也找不到任何东西。有什么想法吗?

谢谢大家。

最佳答案

未经测试,但我会尝试以下操作:

TcpListener listener = new TcpListener(IPAddress.Any, port);
TcpClient client = listener.AcceptTcpClient();

IPEndPoint endPoint = (IPEndPoint) client.Client.RemoteEndPoint;
// .. or LocalEndPoint - depending on which end you want to identify

IPAddress ipAddress = endPoint.Address;

// get the hostname
IPHostEntry hostEntry = Dns.GetHostEntry(ipAddress);
string hostName = hostEntry.HostName;

// get the port
int port = endPoint.Port;

如果您可以使用 IP 地址,我会跳过反向 DNS 查找,但您特别要求提供主机名。

关于c# - 您可以从 System.Net.Sockets.TcpClient 检索主机名和端口吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/409906/

相关文章:

c# - Datagrid 在滚动后选择了错误的行

c# - 如何在解密数据之前检查密码

linux - 审计 Linux 上打开/关闭的端口

networking - 协议(protocol)术语 : Message versus Packet

opencv - MJPEG 网络流到 OpenCV 2

linux - IP header 可以在不同机器上有不同的偏移量吗?

c# - 如何确保生成的 guid 在全局范围内是唯一的?

c# - 我的绑定(bind)源是否可以告诉我是否发生了更改?

c# - 如何在 Web 服务中获取客户端发送的 X509Certificate?

java - Java 中的“ip 路由获取”