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

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

parent 8593d013
...@@ -125,14 +125,16 @@ namespace Misc ...@@ -125,14 +125,16 @@ namespace Misc
} }
catch catch
{ {
try { try
{
IPAddress[] ips = System.Net.Dns.GetHostEntry(s[0]).AddressList; IPAddress[] ips = System.Net.Dns.GetHostEntry(s[0]).AddressList;
if (ips.Length == 1) if (ips.Length == 1)
ip = ips[0]; ip = ips[0];
else else
ip = IPAddress.Parse("127.0.0.1"); ip = IPAddress.Parse("127.0.0.1");
} }
catch{ catch
{
return null; return null;
} }
} }
...@@ -141,6 +143,75 @@ namespace Misc ...@@ -141,6 +143,75 @@ namespace Misc
return null; 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) public static string IPEndPoint2DirectoryName(IPEndPoint ipep)
{ {
return ipep.Address.ToString() + "_" + ipep.Port.ToString(); 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