嗯,你需要绝对知道你是否总是得到一个端口以及你的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 dots 和 1 colon 即可
一些有效IPAddresses的例子(没有端口信息)
IPV4
x.x.x.x
IPV6
x:x:x:x:x:x:x:x
x:x:x:x:x:x:d.d.d.d
: : (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