IPAddress中的端口

我得到一个字符串,代表IP地址。它有格式ip:port我需要生成IPAddress。将用于:

public static IPAddress Parse( string ipString ) 

我需要获取的IPAddress不应包含有关端口的数据。 parse支持吗? 如果不是怎么可能做到的?

那么你需要绝对知道你是否总是随着你的IP获得一个端口。 如果你总是得到一个端口,那么你总是可以使用Jon的代码并在最后一个冒号后删除该部分。

然后您可以将ipString传递给IPAddress.TryParse函数以获取IPAddress对象。

如果ipString因任何原因的格式不正确, IPAddress.Parse函数将给你一个例外。

现在为什么你必须完全知道字符串中port的存在。 让我给你举个例子:

::213 – 绝对有效的IPV6地址。 但它有两个不同的含义:

如果您已经知道必须有一个端口,则转换为0:0:0:0:0:0:0:0:213

但是如果你不知道那么这也意味着0:0:0:0:0:0:0:213 。 请注意,与上面的段相比,只有一个段。 有效的IPV6总是有8个段,我给出的例子是IPV6地址的简写符号。

假设你不知道你是否会在你的字符串中获得一个端口。 那么你必须总是假设IPV6地址是long notation 。 在这种情况下,您可以检查存在的冒号计数(这仅适用于IPV6):(非常粗略的例子)

  int colonCount = ipV6String.Count(c => c == ':'); int dotCount = ipV6String.Count(c=> c== '.'); if (((colonCount == 7) && (dotCount == 3)) || ((colonCount == 8) && (dotCount == 0))) { //Port is present in the string //Extract port using LastIndexOf } else { //Port NOT present } 

为了使其适用于IPV4只需检查3 dots1 colon

有效IPAddresses一些示例(没有端口信息)

IPV4

 xxxx 

IPV6

 x:x:x:x:x:x:x:x x:x:x:x:x:x:dddd : : (short hand notation meaning all the segments are 0s) x: x: : (means that the last six segments are 0s) : : x : x (means that the first six segments are 0s) x : x: : x : x (means the middle four segments are 0s) 

有关IPAddress格式的信息,请检查以下链接:

http://publib.boulder.ibm.com/infocenter/dsichelp/ds8000ic/index.jsp?topic=%2Fcom.ibm.storage.ssic.help.doc%2Ff2c_internetprotocol_3st92x.html

http://publib.boulder.ibm.com/infocenter/ts3500tl/v1r0/index.jsp?topic=%2Fcom.ibm.storage.ts3500.doc%2Fopg_3584_IPv4_IPv6_addresses.html

假设有一个端口并且它总是: ,您可以无条件地删除最后一个冒号后的部分:

 int portStart = ipString.LastIndexOf(':'); ipString = ipString.Substring(0, portStart); 

我希望这也适用于IPv6,除非您的IPv6“地址和端口”格式不使用冒号 – 这与RFC5952一样可行。 基本上要做到这一点,你需要更多地了解你将接收的格式。