2011-02-11 37 views
11

我試圖使用IPAddress.Parse解析包含IP地址和端口的字符串。這適用於IPv6地址,但不適用於IPv4地址。能否解釋爲什麼會發生這種情況?使用IPv4上的端口的IPAddress.Parse()

我正在使用的代碼是:

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

這裏我沒有得到第二個例子的null。我得到一個異常。 IPv4地址不包含端口號。請注意,您正試圖解析包含「IP地址*和*端口」的字符串。所以這個例外是有道理的。爲什麼IPv6版本有效,我不知道。 – 2011-02-11 12:20:04

+4

`IPAddress.Parse(「[:: 1]:5」);`是有效的,*但是*:``5`被無聲丟棄!如果你檢查結果對象,你可以看到結果只是`:: 1`。這可能實際上是`IPAddress.Parse`方法中的一個錯誤... – hangy 2011-02-11 12:29:56

+0

@Martinho Fernandes - 它不是IP6解析器[:1]中的錯誤:5是有效的IP6地址,因爲分隔符是':' ,而不是'::'(http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04#section-4) - **和**合併端口是內置於IP6規範,但IPAddress實體本身不包含*端口。有可能ipv4的[a,b,c,d]:port也是允許的,因爲IP6規範似乎暗示它是IP4規範的一部分 – 2011-02-11 12:46:46

回答

9

發生這種情況是因爲端口不是IP地址的一部分。它屬於TCP/UDP,你必須先將其去掉。 Uri班可能對此有所幫助。

6

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。

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