2012-09-11 28 views
0

我有一個名爲getIP()的方法,它將客戶端ip作爲字符串返回。如何在c#中使用hostip.info服務?

如何使用此IP來獲取使用this服務的客戶端的位置。

這是我如何顯示客戶端的IP地址。

string IP = getIP(); 
lblIPAddress.Text = "IP " + IP; 

我如何在客戶位置中包含?

i.e. lblIPAddress.Text = "IP " + IP+ "location" ;) 

回答

2

下面你可以找到我用得到來自API的XML端點數據前一段時間(我相信這是對API,因此它仍然應該工作完全沒有變化)一個非常簡單的代碼片段:

string city; 
string country; 
string countryCode; 
decimal longitude; 
decimal latitude; 

XmlTextReader hostIPInfoReader = new XmlTextReader("http://api.hostip.info/?ip=" + IP); 
while (hostIPInfoReader.Read()) { 
    if (hostIPInfoReader.IsStartElement()) { 
     if (hostIPInfoReader.Name == "gml:name") 
      city = hostIPInfoReader.ReadString(); 

     if (hostIPInfoReader.Name == "countryName") 
      country = hostIPInfoReader.ReadString(); 

     if (hostIPInfoReader.Name == "countryAbbrev") 
      countryCode = hostIPInfoReader.ReadString(); 

     if (hostIPInfoReader.Name == "gml:coordinates") { 
      string[] coordinates = hostIPInfoReader.ReadString().Split(new char[] { ',' }); 
      longitude = decimal.Parse(coordinates[0]); 
      latitude = decimal.Parse(coordinates[1]); 
     } 
    } 
} 

這段代碼當然可以改進,但我相信這是一個很好的起點。

+0

工作就像一個魅力... thanx:D –