IPAddress.Parse()使用IPv4上的端口

时间:2011-02-11 12:07:02

标签: c# .net ip-address tcp-port

我正在尝试使用IPAddress.Parse解析包含IP地址和端口的字符串。这适用于IPv6地址但不适用于IPv4地址。可以解释为什么会发生这种情况吗?

我正在使用的代码是:

IPAddress.Parse("[::1]:5"); //Valid
IPAddress.Parse("127.0.0.1:5"); //null

5 个答案:

答案 0 :(得分:19)

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);
}

答案 1 :(得分:11)

这是因为端口不是IP地址的一部分。它属于TCP / UDP,您必须先将其删除。 Uri类可能对此有所帮助。

答案 2 :(得分:7)

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);
      }
   }
}

编辑:好的,我承认这不是最优雅的解决方案。试试这个我(仅为你)写的:

// 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));
}

请注意,这一个只接受IP地址,而不是主机名。如果要支持主机名,则必须将其解析为IP或不使用IPAddress / IPEndPoint。

答案 3 :(得分:5)

IPAddress.Parse用于获取一个字符串,该字符串包含IPv4的dot-quad表示法的IP地址和IPv6的冒号十六进制表示法。因此,您的第一个示例适用于IPv6,而您的第二个示例失败,因为它不支持IPv4端口。链接http://msdn.microsoft.com/en-us/library/system.net.ipaddress.parse.aspx

答案 4 :(得分:0)

正如 Tedd Hansen 指出的那样,您尝试解析的不是 IP 地址,而是 IP 端点(IP 地址 + 端口)。从 .NET Core 3.0 开始,您可以使用 IPEndPoint.TryParse 将字符串解析为 IPEndPoint:

if (IPEndPoint.TryParse("127.0.0.1:5", out IPEndPoint endpoint))
{
    // parsed successfully, you can use the "endpoint" variable
}
else
{
    // failed to parse
}