gpt4 book ai didi

c# - 从字符串创建 IPEndpoint 的最佳方法

转载 作者:IT王子 更新时间:2023-10-29 03:59:44 24 4
gpt4 key购买 nike

因为 IPEndpoint 包含一个 ToString() 方法输出:

10.10.10.10:1010

还应该有 Parse() 和/或 TryParse() 方法,但没有。

我可以在 : 上拆分字符串并解析 IP 地址和端口。

但是有没有更优雅的方式呢?

最佳答案

这是一个解决方案...

public static IPEndPoint CreateIPEndPoint(string endPoint)
{
string[] ep = endPoint.Split(':');
if(ep.Length != 2) throw new FormatException("Invalid endpoint format");
IPAddress ip;
if(!IPAddress.TryParse(ep[0], out ip))
{
throw new FormatException("Invalid ip-adress");
}
int port;
if(!int.TryParse(ep[1], NumberStyles.None, NumberFormatInfo.CurrentInfo, out port))
{
throw new FormatException("Invalid port");
}
return new IPEndPoint(ip, port);
}

编辑:添加了一个将处理 IPv4 和 IPv6 的版本,之前的版本仅处理 IPv4。

// Handles IPv4 and IPv6 notation.
public static IPEndPoint CreateIPEndPoint(string endPoint)
{
string[] ep = endPoint.Split(':');
if (ep.Length < 2) throw new FormatException("Invalid endpoint format");
IPAddress ip;
if (ep.Length > 2)
{
if (!IPAddress.TryParse(string.Join(":", ep, 0, ep.Length - 1), out ip))
{
throw new FormatException("Invalid ip-adress");
}
}
else
{
if (!IPAddress.TryParse(ep[0], out ip))
{
throw new FormatException("Invalid ip-adress");
}
}
int port;
if (!int.TryParse(ep[ep.Length - 1], NumberStyles.None, NumberFormatInfo.CurrentInfo, out port))
{
throw new FormatException("Invalid port");
}
return new IPEndPoint(ip, port);
}

关于c# - 从字符串创建 IPEndpoint 的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2727609/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com