如何获取正在运行的 TcpListener 的 fqdn



我有一个由TcpListener表示的服务器,我需要它的FQDN。有没有办法得到它?侦听器定义为:

TcpListener tcpListener = new TcpListener(IPAddress.Any, 27015);

我的简短回答是构造 FQDN 的简单方法。如果您的服务器实现多个网络接口,则此操作可能会失败。

public string FQDN() {
  string host = System.Net.Dns.GetHostName();
  string domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;      
  return host + "." + domain;
}


由于您正在使用IPAddress.Any初始化TCPListener,根据MSDN

基础服务提供商将分配最合适的网络地址。

这意味着,您必须等到客户端连接才能检索 FQDN,因为您事先不知道将分配哪个网络地址(再一次,如果您的服务器实现了多个网络接口,您不知道客户端将连接到哪一个)。
获取客户端连接到的网络接口的 FQDN 需要三个步骤:

  1. 获取客户端的本地终结点(作为 IPEndPoint)
  2. 获取端点的 IP 地址
  3. 获取此 IP 地址的主机条目(通过 Dns.GetHostEntry)

在代码中,它看起来像这样:

//using System.Net
//using System.Net.Sockets
TcpListener tcpListener = new TcpListener(IPAddress.Any, 27015);
tcpListener.Start();
//code to wait for a client to connect, omitted for simplicity
TcpClient connectedClient = tcpListener.AcceptTcpClient(); 
//#1: retrieve the local endpoint of the client (on the server)
IPEndPoint clientEndPoint = (IPEndPoint)connectedClient.Client.LocalEndPoint;
//#2: get the ip-address of the endpoint (and cast it to string)
string connectedToAddress = clientEndPoint.Address.ToString();
//#3: retrieve the host entry from the dns for the ip address
IPHostEntry hostEntry = Dns.GetHostEntry(connectedToAddress);
//print the fqdn
Console.WriteLine("FQDN: " + hostEntry.HostName);

您可以在一行中写 #1、#2 和 #3:

Dns.GetHostEntry(((IPEndPoint)connectedClient.Client.LocalEndPoint).Address.ToString()).HostName);

最新更新