开发者

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.


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

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


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 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜