Fra*_*lva 12 .net c# ip-address tcp-port
我正在尝试使用IPAddress.Parse解析包含IP地址和端口的字符串.这适用于IPv6地址但不适用于IPv4地址.可以解释为什么会发生这种情况吗?
我正在使用的代码是:
IPAddress.Parse("[::1]:5"); //Valid
IPAddress.Parse("127.0.0.1:5"); //null
Run Code Online (Sandbox Code Playgroud)
aba*_*hev 22
Uri url;
IPAddress ip;
if (Uri.TryCreate(String.Format("http://{0}", "127.0.0.1:5"), UriKind.Absolute, out url) &&
IPAddress.TryParse(url.Host, out ip))
{
IPEndPoint endPoint = new IPEndPoint(ip, url.Port);
}
Run Code Online (Sandbox Code Playgroud)
IPAddress不是IP +端口.你想要IPEndPoint.
来自http://www.java2s.com/Code/CSharp/Network/ParseHostString.htm的示例
public static void ParseHostString(string hostString, ref string hostName, ref int port)
{
hostName = hostString;
if (hostString.Contains(":"))
{
string[] hostParts = hostString.Split(':');
if (hostParts.Length == 2)
{
hostName = hostParts[0];
int.TryParse(hostParts[1], out port);
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:好的,我承认这不是最优雅的解决方案.尝试这个我写的(只为你)而不是:
// You need to include some usings:
using System.Text.RegularExpressions;
using System.Net;
// Then this code (static is not required):
private static Regex hostPortMatch = new Regex(@"^(?<ip>(?:\[[\da-fA-F:]+\])|(?:\d{1,3}\.){3}\d{1,3})(?::(?<port>\d+))?$", System.Text.RegularExpressions.RegexOptions.Compiled);
public static IPEndPoint ParseHostPort(string hostPort)
{
Match match = hostPortMatch.Match(hostPort);
if (!match.Success)
return null;
return new IPEndPoint(IPAddress.Parse(match.Groups["ip"].Value), int.Parse(match.Groups["port"].Value));
}
Run Code Online (Sandbox Code Playgroud)
请注意,这个只接受IP地址,而不是主机名.如果要支持主机名,则必须将其解析为IP或不使用IPAddress/IPEndPoint.
IPAddress.Parse用于获取一个字符串,该字符串包含IPv4的点分四位表示法的IP地址和IPv6的冒号十六进制表示法.因此,您的第一个示例适用于IPv6,而您的第二个示例失败,因为它不支持IPv4端口.链接http://msdn.microsoft.com/en-us/library/system.net.ipaddress.parse.aspx
归档时间: |
|
查看次数: |
16409 次 |
最近记录: |