3

如何在我的 ASP.NET 页面中查找客户端位置?事实上我用过System.Globalization.RegionInfo.CurrentRegion,但它在控制面板中显示设置。那么我可以使用任何方法找到确切的位置吗?

4

3 回答 3

5

Not that it would give you 100% accuracy, but you can use hostip.info

They provide an API that gives you the location of an IP address that you pass them via HTTP request. You can use a WebClient object to make calls to the API and parse the results. Scott Hanselman has a pretty great example in this blog article (my example below is based on his article). hostip.info's database is based on an open project that the community contributes IP locations to... so there is no guarantee to be correct.

For starters, you need to determine the client IP address as follows:

string ipaddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

Once you have the IP, you can create a WebClient object and call the API...

Example API call:

string r;
using (var w = new WebClient())
{
    r = w.DownloadString(String.Format("http://api.hostip.info/?ip={0}&position=true", ipaddress));
}

The results will be XML that looks something like this:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<HostipLookupResultSet version="1.0.0" xmlns="http://www.hostip.info/api" xmlns:gml="http://www.opengis.net/gml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.hostip.info/api/hostip-1.0.0.xsd">
 <gml:description>This is the Hostip Lookup Service</gml:description>
 <gml:name>hostip</gml:name>
 <gml:boundedBy>
    <gml:Null>inapplicable</gml:Null>
 </gml:boundedBy>
 <gml:featureMember>
    <Hostip>
     <gml:name>Sugar Grove, IL</gml:name>
     <countryName>UNITED STATES</countryName>
     <countryAbbrev>US</countryAbbrev>
     <!-- Co-ordinates are available as lng,lat -->
     <ipLocation>
        <gml:PointProperty>
         <gml:Point srsName="http://www.opengis.net/gml/srs/epsg.xml#4326">
            <gml:coordinates>-88.4588,41.7696</gml:coordinates>
         </gml:Point>
        </gml:PointProperty>
     </ipLocation>
    </Hostip>
 </gml:featureMember>
</HostipLookupResultSet>
于 2009-08-06T11:04:53.407 回答
3

如果您想要的只是 IP 地址所在的国家/地区, IPAddressExtensions是一个免费的CodePlex类库。

它不需要连接到另一个网站等。而且它是开源的..所以发疯了;)

于 2009-09-30T08:59:40.970 回答
1

You can guess country that the IP address belongs to by doing a lookup to client IP address. There are some pages that provide databases containing IP to country mapping tables., see here for example

于 2009-08-06T10:57:03.470 回答