2011-04-22 72 views
0

嗨 我有一個需要從URL中提取IP。下面的代碼是工作在一個案例:GetHostByName錯誤與http鏈接獲取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()); 
} 

但是,如果改變URL作爲

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

GetHostByName拋出異常。

我應該在哪種情況下使用哪種方法?

+0

取決於我得到的答案。 – CrazyC 2011-04-22 09:44:14

回答

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

也MSDN說Dns.GetHostByName是過時了,你應該使用Dns.GetHostEntry代替。

+1

+1代表'Dns.GetHostByName'陳舊過時。 – 2011-04-22 10:04:21

+0

/同意@ AS-CII – 2012-01-19 13:49:55