Get City and Country from IP

HOME
FORUM
ARTICLES
TUTORIALS
SCRIPTS
LINKS
NEWS
MENTORS
TOOLS
REGISTER

Sorry our partner site rodsdot is currently down. Please try again later

Geo-Coding IP Addresses

Rod Divilbiss
2/6/2006

"Cities, like cats, will reveal themselves at night."
                                           Rupert Brook

It seems to have become increasingly popular to display the city and country of the browser visiting your web site in the web page.  Obtaining the city, country and/or coordinates on the globe from an IP address is called geo-coding.

There are several commercial sites that expose a web service or application programming interface (API) for you to get the geographic location of an IP address. This simple tutorial will show a quick and simple method to do this using a custom object written in ASP and the GPL "hostip" database maintained at http://www.hostip.info/.

The hostip project was founded by Simon Gornall as a community effort to build a non-commercial geo-coded database of IP addresses. If you use the service, please consider a contribution, of any amount, to help defray the cost of hosting and maintaining the database. You can imagine what the bandwidth expenses must be for a popular database such as this.

To use the ASP class in your page you need only to add one line to your pages code.

browserLocale Include
<!--#include file="browserLocale.asp"-->

The "browserLocale" object is automatically created on page load and its properties loaded with the geo-code information corresponding to your visitors IP address.  The five properties exposed by the browserLocale object are;

  1. .city
  2. .country
  3. .ip
  4. .longitude
  5. .latitude

To write your visitor's city and country to the page you simply write the city and country properties.

Write The Vistor's Country
<%
response.write browserLocale.city & " " & browserLocale.country
%>

There is no coding necessary on your part. There is no subscription to buy. You need no registration or access key. Just include one line at the top of your page and use the five properties as needed.

The class containing the browserLocale object is only a few lines of code and uses remote scripting to access the hostip.info's api. A tiny XML file is returned from hostip.info and is parsed into the properties and made available for use. The browserLocale object also has one method, ".spill" which will write all five properties to the browser in a table.  The listing below is an example page using the spill method which is useful for testing the object. [Try the spill method live]

Example browserLocale Page
<!--#include file="getBrowserLocale.asp"-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="author" content="Roderick Divilbiss">
<meta name="copyright" content="© 2005 Roderick Divilbiss">
<title>Geocode IP</title>
</head>

<body>
<p><% browserLocale.spill %></p>
</body>

</html>
 

And finally, the browserLocale class file.

browserLocale Class
<%
class browserLocaleObject
    public city
    public country
    public longitude
    public latitude
    public ip

    Private sub Class_Initialize
        Dim objXMLHTTP
        Dim coordinates
        Set objXMLHTTP = Server.CreateObject("Microsoft.XMLHTTP")
        ip = Request.ServerVariables("REMOTE_ADDR")
        objXMLHTTP.Open "GET", "http://api.hostip.info/?ip="&ip, False
        objXMLHTTP.Send
        Set xmldoc = objXMLHTTP.responseXML
        city = xmldoc.selectSingleNode("HostipLookupResultSet/gml:featureMember/Hostip/gml:name").text
        country = xmldoc.selectSingleNode("HostipLookupResultSet/gml:featureMember/Hostip/countryName").text
        coordinates = Split(xmldoc.selectSingleNode("HostipLookupResultSet/gml:featureMember/Hostip/ipLocation").text,",")
        longitude = coordinates(0)
        latitude = coordinates(1)
        set objXMLHTTP=nothing
    End sub

    Public Sub Spill
        Dim out
        out = "<table>"
        out = out & "<tr><td width=""50%"">City</td><td width=""50%"">" & city & "</td></tr>"
        out = out & "<tr><td width=""50%"">Country</td><td width=""50%"">" & country & "</td></tr>"
        out = out & "<tr><td width=""50%"">IP</td><td width=""50%"">" & ip & "</td></tr>"
        out = out & "<tr><td width=""50%"">Longitude</td><td width=""50%"">" & longitude & "</td></tr>"
        out = out & "<tr><td width=""50%"">Latitude</td><td width=""50%"">" & latitude & "</td></tr>"
        out = out & "</table>"
        response.write out
    End Sub
End class

Dim browserLocale
Set browserLocale = new browserLocaleObject
%>
 

With a one-line include you have your visitor's IP address geo-coded.  Note it is simple to provide PHP and JavaScript versions of this object and I hope to post those tutorials soon.  Feel free to help yourself to the source code and examples at the link below.

Source for the browserLocale class and examples.


Other Remote Scripting Articles By This Author

AJAHT (AJAX isn't just for XML)
Including Files with JavaScript (No IFRAME, No Hacks)
Remote Scripting Images !AJAX
Please Wait! (Letting the user know an AJAX call is pending)
HTTP communications with a Server
Reading A Web Server's Response Headers





A picture of Roderick (Rod) Divilbiss taken June 2005. Visit Rod at www.rodsdot.com.
Creative Commons License© 2006 Rod Divilbiss.
Except where otherwise noted, this content is licensed under a Creative Commons License Creative Commons License.
Content provided exclusively for Experts Round Table by Rod Divilbiss web developer and restaurateur.
Visit Rod at <!--rodsdot.com--> or in person at Cafe Song
e-mail author
Page viewed 20343 times.
post to Dzone Digg this! Add to del.icio.us Googleize this Add to reddit Save to myYahoo Add to furl Add to Netvouz! Spurl this! Add to Linkroll! Save to Simpy Give if thumbs up on StumbleUpon Save to Blinklist Add to Tektag Save to Bibsonomy Submit to Tweako
Search ERT on the Tools Page
Did you know? You can discuss this article with the mentor who wrote it and others interested in the topic? You are invited to join the discussion with Go to the forum

Got a technical article or tutorial you want to publish on the Internet? Join Go to the forum in the Round Table Forum and let the Mentors know what you have. If it meets ERT standards, is factual and can help ERT visitors, then ERT Mentors and Editors can help you (without charge) polish your offering so it can be published and promoted by ERT. An article published on ERT may be read by as many as 10,000 visitors a week; promoting you, your site, and your ideas. Please note ERT does not publish re-prints; promotional handouts, or pieces consisting mainly of links. So original technical content only please. If you prefer you can email the Editor