dko
dko

Reputation: 904

Parsing IP Address in .NET

I have a string that can either represent a host name (myip.noip.org, etc.) or it can represent a true address ("127.0.0.1"). What is the best way to resolve this to a System.Net.IPAddress?

Thanks in advance.

Upvotes: 5

Views: 582

Answers (3)

Oded
Oded

Reputation: 499352

Use the IPAddress.Parse method for IP addresses.

IPAddress address = IPAddress.Parse("127.0.0.1");

As mentioned by others, to resolve both IP addresses and host names, use Dns.GetHostEntry which:

Resolves a host name or IP address to an IPHostEntry instance.

IPHostEntry holds a collection of IP addresses in its AddressList property.

Upvotes: 1

JaredPar
JaredPar

Reputation: 755447

Use the Dns.GetHostAddresses method. This will handle both domain names and raw IP address values

IPAddress[] array = DNs.GetHostAddresses(theString);

Upvotes: 6

SLaks
SLaks

Reputation: 888157

You can call Dns.GetHostEntry on an IP address or a hostname.
It even does reverse lookups for you.

If you don't need reverse lookup, you can call Dns.GetHostAddresses instead.

Upvotes: 6

Related Questions