开发者

GetHostByName error with http link to get IP address

开发者 https://www.devze.com 2023-02-28 15:25 出处:网络
Hi I have a requirement where extract the IP from URL. The following code is working in one case: string str2 = \"www.google.com\";

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

精彩评论

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