I get a string ,representing ip address .It has format ip:port I need to generate IPAddress .Will use for that :
public static IPAddress Parse(
string ipString
)
The IPAddress which I need to get should not contain the data regarding a port.
Does parse
support that? If not how is it possible to done?
Assuming there's there's always a port and it's always represented by
:<port number>
, you can just unconditionally remove the part after the last colon:I would expect that to work with IPv6 as well, unless your IPv6 "address and port" format doesn't use a colon - as is feasible with RFC5952. Basically to do this well, you'll need to have more of an idea of the format you'll be receiving.
Well you need to absolutely know whether you are ALWAYS getting a port along with your
IP
or not. If you are always getting a port then you can always use Jon's code and get rid of the part after the last colon.The
ipString
then you can pass on to theIPAddress.TryParse
function to get the IPAddress object.The
IPAddress.Parse
function will give you an exception if theipString
for whatever reason is not in a correct format.Now why do you have to absolutely know about the existence of the
port
in the string. Let me give you an example:::213
- An absolutely valid IPV6 address. But it has two different meanings:If you already know there must be a port then this translates to
0:0:0:0:0:0:0:0:213
.But if you do not know then this can also mean
0:0:0:0:0:0:0:213
. Note there is one less segment as compared to the above one. A valid IPV6 always has 8 segments, the example i am giving is the shorthand notation for a IPV6 address.Let's say you do not know whether you would be getting a port in your string or not. Then you MUST always assume that IPV6 addresses would be in the
long notation
. In which case you can check for the count of colons present like so (this is only for IPV6): (Very crude example)To make this workable for
IPV4
just check for3 dots
and1 colon
as wellSome examples of valid
IPAddresses
(without port information)IPV4
IPV6
Please check these following links as well for information about IPAddress formats:
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