GetHostByName错误,http链接获取IP地址

Cra*_*zyC 0 .net c#

嗨我有一个要求从URL中提取IP.以下代码适用于一种情况:

string str2 = "www.google.com";
IPHostEntry ip = Dns.GetHostByName(str2);
IPAddress [] IpA = ip.AddressList;
for (int i = 0; i < IpA.Length; i++)
{
    Console.WriteLine ("IP Address {0}: {1} ", i, IpA[i].ToString ());
}
Run Code Online (Sandbox Code Playgroud)

但是如果将URL更改为

string str2 = "http://google.com";
Run Code Online (Sandbox Code Playgroud)

GetHostByName 抛出异常.

在这两种情况下我应该使用哪种方法?

Ale*_*lex 5

您可以使用Uri.IsWellFormedUriString方法来确定是否str2格式正确,然后仅获取主机:

string str2 = "http://www.google.com";
if (Uri.IsWellFormedUriString(str2, UriKind.Absolute))
{
    str2 = new Uri(str2).Host;
}
var host = Dns.GetHostEntry(str2);
Run Code Online (Sandbox Code Playgroud)

MSDN也说它Dns.GetHostByName已经过时了,你应该使用它Dns.GetHostEntry.