C# 如何获取正在运行的TcpListener的fqdn
我有一个由TcpListener表示的服务器,我需要它的FQDN。 有什么办法可以得到它吗? 侦听器定义为:C# 如何获取正在运行的TcpListener的fqdn,c#,tcplistener,C#,Tcplistener,我有一个由TcpListener表示的服务器,我需要它的FQDN。 有什么办法可以得到它吗? 侦听器定义为: TcpListener tcpListener = new TcpListener(IPAddress.Any, 27015); 我的简短回答是构造FQDN的简单方法。如果服务器实现多个网络接口,则此操作可能会失败 public string FQDN() { string host = System.Net.Dns.GetHostName(); string domain =
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初始化TCPListener
。根据
基础服务提供商将分配最合适的网络地址
这意味着,您必须等待客户端连接后才能检索FQDN,因为您事先不知道将分配什么网络地址(同样,如果您的服务器实现多个网络接口,您也不知道客户端将连接到哪个网络接口)。
获取客户端连接到的网络接口的FQDN需要三个步骤:
获取客户端的本地端点(作为
获取端点的IP地址
获取此IP地址的主机条目(通过)
在代码中,它如下所示:
//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);
你说的“我有一台服务器”是什么意思,所以它是你的本地主机?你可以从FQDN获得ip地址,但不能从ip地址获得FDQN