开发者

GetHostByName error with http link to get IP address

Hi I have a requirement where extract the IP from URL. The following code is working in one case:

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 ());
}

But if change the URL as

string str2 = "http://google.com";

GetHostByName is throwing exception.

What method I should use which work in both cases?


You could use Uri.IsWellFormedUriString method to determine whether the str2 is well-formed and then get the host only:

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

also MSDN says that Dns.GetHostByName is obsolete, and you should use Dns.GetHostEntry instead.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜