Commit b168f3fa authored by 潘栩锋's avatar 潘栩锋 🚴

添加 扩展 Misc.StringConverter.ToIPEndPoint 支持转换异常时,使用默认值.

parent 8593d013
......@@ -125,14 +125,16 @@ namespace Misc
}
catch
{
try {
try
{
IPAddress[] ips = System.Net.Dns.GetHostEntry(s[0]).AddressList;
if (ips.Length == 1)
ip = ips[0];
else
ip = IPAddress.Parse("127.0.0.1");
}
catch{
catch
{
return null;
}
}
......@@ -141,6 +143,75 @@ namespace Misc
return null;
}
// 摘要:
// 将主机名或 IP 地址解析为 IPEndPoint 实例。
public static IPEndPoint ToIPEndPoint(string hostNameOrAddress, IPAddress default_address, int default_port)
{
IPAddress ip = default_address;
int port = default_port;
if (string.IsNullOrEmpty(hostNameOrAddress))
{
return new IPEndPoint(ip, port);
}
string[] s = hostNameOrAddress.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
if (s.Length == 1)
{
try
{
ip = IPAddress.Parse(s[0]);
}
catch
{
try
{
IPAddress[] ips = System.Net.Dns.GetHostEntry(s[0]).AddressList;
if (ips.Length == 1)
ip = ips[0];
}
catch
{
}
}
}
else if (s.Length == 2)
{
try
{
port = int.Parse(s[1]);
}
catch
{
}
try
{
ip = IPAddress.Parse(s[0]);
}
catch
{
try
{
IPAddress[] ips = System.Net.Dns.GetHostEntry(s[0]).AddressList;
if (ips.Length == 1)
ip = ips[0];
}
catch
{
}
}
}
return new IPEndPoint(ip, port);
}
public static string IPEndPoint2DirectoryName(IPEndPoint ipep)
{
return ipep.Address.ToString() + "_" + ipep.Port.ToString();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment