65.9K
CodeProject 正在变化。 阅读更多。
Home

轻松跟踪基于 IP 地址的地理位置

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.80/5 (38投票s)

2010年3月2日

CPOL

2分钟阅读

viewsIcon

169620

downloadIcon

5718

轻松跟踪基于 IP 地址的地理位置。

目录

引言

开发人员非常熟悉IP跟踪系统的使用,Microsoft Visual Studio .NET 提供了许多类和方法来实现这一点。本文不仅仅是关于获取用户IP,还包括查找浏览您ASP.NET应用程序的用户的地理位置。例如,您有一个ASP.NET应用程序,已经托管,您的网址假设为“www.xyz.com”,现在您想跟踪/维护访客IP和位置的日志,类似这样:

IP: XXX.XXX.XXX.XXX, TIMESTAMP: 3/2/2010 4:18:39 PM, COUNTRY= BANGLADESH, 
COUNTRY CODE= BD, CITY= DHAKA, etc.

示例输出图

快速概览

在我们开始之前,我们需要了解一些基本知识,关于Microsoft Visual Studio .Net提供的System.NetSystem.Data命名空间,以及HTTP服务器变量。

有关更多信息,请访问此链接

如何实现

如果您在互联网上搜索解决方案,您可能会找到很多方法。例如,您可以使用Web服务或下载包含IP映射位置的数据库,但其中大多数并不免费使用/每天只允许您访问非常有限的次数……我发现一些网站允许您免费获取用户IP位置,以下列出了一些网站:

注意:以上列出的所有地址都以标准XML格式回复。

如何使用服务

在本节中,我想讨论如何使用这些网站来检索用户的地理位置。您可以选择其中任何一个,在此之前,您需要了解需要哪些参数,让我们一个一个地开始。

(i)http://freegeoip.appspot.com

参数:IP地址 (xxx.xxx.xxx.xxx)。
URL示例:http://freegeoip.appspot.com/xml/xxx.xxx.xxx.xxx
输出:标准XML

<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Status>true</Status>
    <Ip>xxx.xxx.xxx.xxx</Ip>
    <CountryCode>BD</CountryCode>
    <CountryName>Bangladesh</CountryName>
    <RegionCode>81</RegionCode>
    <RegionName>Dhaka</RegionName>
    <City>Dhaka</City>
    <ZipCode></ZipCode>
    <Latitude>23.723</Latitude>
    <Longitude>90.4086</Longitude>
</Response>
(ii)http://ws.cdyne.com/
  • 参数:IP地址 (xxx.xxx.xxx.xxx) & 许可证密钥
  • URL示例:http://ws.cdyne.com/ip2geo/ip2geo.asmx/ResolveIP?ipAddress=xxx.xxx.xxx.xxx&licenseKey=0
  • 输出:标准XML
<?xml version="1.0" encoding="utf-8"?>
<IPInformation xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance 
	xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://ws.cdyne.com/">
  <City>Dhaka</City>
  <StateProvince>81</StateProvince>
  <Country>Bangladesh</Country>
  <Organization />
  <Latitude>23.72301</Latitude>
  <Longitude>90.4086</Longitude>
  <AreaCode>0</AreaCode>
  <TimeZone />
  <HasDaylightSavings>false</HasDaylightSavings>
  <Certainty>90</Certainty>
  <RegionName />
  <CountryCode>BD</CountryCode>
</IPInformation>

代码块应设置为“格式化”样式,如下所示

(iii)http://ipinfodb.com/
  • 参数:IP地址 (xxx.xxx.xxx.xxx)
  • URL示例:http://ipinfodb.com/ip_query.php?ip=xxx.xxx.xxx.xxx0
  • 输出:标准XML
<?xml version="1.0" encoding="UTF-8"?>
<Response>
  <Ip>xxx.xxx.xxx.xxx</Ip>
  <Status>OK</Status>
  <CountryCode>BD</CountryCode>
  <CountryName>Bangladesh</CountryName>
  <RegionCode>81</RegionCode>
  <RegionName>Dhaka</RegionName>
  <City>Dhaka</City>
  <ZipPostalCode></ZipPostalCode>
  <Latitude>23.7231</Latitude>
  <Longitude>90.4086</Longitude>
  <Timezone>6</Timezone>
  <Gmtoffset>6</Gmtoffset>
  <Dstoffset>6</Dstoffset>
</Response>

获取用户IP

我使用了一种非常常见的技术。实际上,这只不过是使用了HTTP服务器变量。以下服务器变量用于此目的。

  • HTTP_X_FORWARDED_FOR
  • REMOTE_ADDR

以下是一个示例代码片段

private string GetVisitor()
    {        
        string strIPAddress = string.Empty;
        string strVisitorCountry = string.Empty;

        strIPAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

        if (strIPAddress == "" || strIPAddress == null)
            strIPAddress = Request.ServerVariables["REMOTE_ADDR"];

        Tools.GetLocation.IVisitorsGeographicalLocation _objLocation;
        _objLocation = new Tools.GetLocation.ClsVisitorsGeographicalLocation();

        DataTable _objDataTable = _objLocation.GetLocation(strIPAddress);

        if (_objDataTable != null)
        {
            if (_objDataTable.Rows.Count > 0)
            {
                strVisitorCountry = 
                            "IP: "
                            + strIPAddress
                            + ", TIMESTAMP: " 
                            + Convert.ToString(System.DateTime.Now)     
                            + ", CITY: "
                            + Convert.ToString(_objDataTable.Rows[0]["City"]).ToUpper()
                            + ", COUNTRY: "
                            + Convert.ToString(_objDataTable.Rows[0]
					["CountryName"]).ToUpper()
                            + ", COUNTRY CODE: "
                            + Convert.ToString(_objDataTable.Rows[0]
					["CountryCode"]).ToUpper();
            }
            else
            {
                strVisitorCountry = null;
            }
        }
        return strVisitorCountry;
    }

获取用户位置

要获取位置,您只需要使用Microsoft Visual Studio .NET提供的以下功能。

  • WebRequest
  • WebResponse
  • WebProxy

有关更多信息,请访问此链接

以下是一个示例代码片段

public DataTable GetLocation(string strIPAddress)
        {
            //Create a WebRequest with the current Ip
            WebRequest _objWebRequest =
                WebRequest.Create(http://freegeoip.appspot.com/xml/ 
		//http://ipinfodb.com/ip_query.php?ip=
                               + strIPAddress);
            //Create a Web Proxy
            WebProxy _objWebProxy =
               new WebProxy("http://freegeoip.appspot.com/xml/"
                         + strIPAddress, true);

            //Assign the proxy to the WebRequest
            _objWebRequest.Proxy = _objWebProxy;

            //Set the timeout in Seconds for the WebRequest
            _objWebRequest.Timeout = 2000;

            try
            {
                //Get the WebResponse 
                WebResponse _objWebResponse = _objWebRequest.GetResponse();
                //Read the Response in a XMLTextReader
                XmlTextReader _objXmlTextReader
                    = new XmlTextReader(_objWebResponse.GetResponseStream());

                //Create a new DataSet
                DataSet _objDataSet = new DataSet();
                //Read the Response into the DataSet
                _objDataSet.ReadXml(_objXmlTextReader);

                return _objDataSet.Tables[0];
            }
            catch
            {
                return null;
            }
        } // End of GetLocation		 

结论

希望这对您有所帮助!祝您使用愉快。

参考文献

  • MSDN

历史

  • 2010年3月2日:初次发布
© . All rights reserved.