简体   繁体   中英

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.

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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM