2010年10月28日 星期四

利用 XElement 類別擷取 IP 所在之國家 ( Country )

引用網址:http://byteblocks.com/post/2009/06/01/Convert-IP-To-Location-and-Address-To-Location.aspx

首先,利用 WebClient 類別下載網頁原始碼那是必需的,但最重要的是要有網頁能提供 IP 查詢國家所在,所以找到了 http://ipinfodb.com/ip_query.php 這網頁,此網頁不吃參數時,預設會找出你電腦 IP 的相關資料( 包含電腦所在國家 ),但若吃 ip 參數時,就會列出此 ip 相關參數,例如:
http://ipinfodb.com/ip_query.php?ip=61.219.38.89
此 ip 為中華電信之 IP。

所以若要以 IP 找出相關資料,可利用以下程式擷取出來。
static void Main(string[] args)
{
string Ip = "61.219.38.89"; /* 中華電信 IP */
string Url = string.Format("http://ipinfodb.com/ip_query.php?ip={0}", Ip);
string Content = GetUrlContent(Url);

StringReader sr = new StringReader(Content);
XElement xe = XElement.Load(sr);
string strStatus = Convert.ToString(xe.Element("Status").Value);

if (string.Compare(strStatus, "OK", true) == 0)
{
Console.WriteLine(Convert.ToString(xe.Element("CountryName").Value));
}
}

static string GetUrlContent(string Url)
{
string content = string.Empty;
WebClient client = new WebClient();
try
{
content = client.DownloadString(Url);
}
catch (WebException we)
{
content = we.Message;
}
return content;
}
最後,只要依據 IP 的不同,就能擷取出 IP 的相關資料。

回目錄
回首頁

沒有留言 :

張貼留言

Related Posts Plugin for WordPress, Blogger...