对于我的 .NET C# 应用程序,我们有一些模块需要通过 TCP/IP 协议(protocol)进行通信。
我决定使用 Microsoft 的 System.Net.Sockets API
“TcpListener”类代表的模块可以是
-基于IPv4地址 -基于IPv6地址
问题是使用“TcpClient”类的模块需要以智能获取 IPv4 或 IPv6 地址(最初作为字符串传递)的方式实例化“TcpClient”
详细来说,使用“TcpClient”类的模块可以有如下构造函数:
public ClientModule(string ipV4OrIpV6Address, int portNumber){
………………………
…………..
……….
}
当我查看 Microsoft 的文档 (https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.tcpclient.-ctor?view=netframework-4.8#System_Net_Sockets_TcpClient__ctor_System_Net_IPEndPoint_) 时,我发现了以下 TcpClient 构造函数:
TcpClient(IPEndPoint)
Initializes a new instance of the TcpClient class and binds it to the specified local endpoint.
此外,我尝试搜索更多关于实例化 IPEndPoint 类的信息,我遇到了 ( https://learn.microsoft.com/en-us/dotnet/api/system.net.ipendpoint.-ctor?view=netframework-4.8#System_Net_IPEndPoint__ctor_System_Net_IPAddress_System_Int32_)
每个模块将位于不同的物理计算机服务器上。
我如何着手实例化 Microsoft 的 IPAddress 对象,使其足够智能以将 IPv4 和 IPv6 地址作为字符串处理,而不管哪个作为参数传递?
最佳答案
使用IPAddress.Parse(string ipAddress)构建端点。
它接受包含 IPv4 点分十进制表示法或 IPv6 冒号分隔地址字符串的字符串,并返回 System.Net.IPAddress
。
public void ClientModule(string ipV4OrIpV6Address, int portNumber)
{
IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(ipV4OrIpV6Address), int port);
TcpClient client = new TcpClient(endpoint);
// Do something with the client
}
关于c# - 如何实现 TcpClient、IPEndPoint、IPAddress 对象的实例化,当作为字符串传递时,为这两种情况实例化 IPv4 和 IPv6 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56745408/