Program.in

By Santosh Wadghule

IP address location in Ruby and Rails…

with 3 comments

Here,  I have made code that converts the IP address to the location using IP location tools. Code parses the XML file of IP Address Location and returns the string that contains location  of IP Address.  Code is below…

require 'net/http'
require 'rexml/document'
include REXML

class MapsController < ApplicationController
	def index
		@location = locateIp()

	end

	def locateIp
		#ip = "123.123.123.123";
		ip = request.remote_ip
		ips = ip.to_s
		url = "http://iplocationtools.com/ip_query.php?ip="+ips

		xml_data = Net::HTTP.get_response(URI.parse(url)).body

                xmldoc = REXML::Document.new(xml_data)

		# Now get the root element
		root = xmldoc.root
		city = ""
		regionName = ""
		countryName = ""

		# This will take country name...
		xmldoc.elements.each("Response/CountryName") {
		|e| countryName << e.text
	    }

		# Now get city name...
		xmldoc.elements.each("Response/City") {
   		|e| city << e.text
	    }

		# This will take regionName...
		xmldoc.elements.each("Response/RegionName") {
   		|e| regionName << e.text
	    }

     	ipLocation = city +", "+regionName+", "+countryName

	 return ipLocation
   end #end of method locateIp

end

Written by Santosh Wadghule

April 11, 2009 at 7:49 pm

Posted in Ruby

3 Responses

Subscribe to comments with RSS.

  1. I am just wondering, your code relies on availability of http://iplocationtools.com . What if for whatever reason service is not available. Any work around that?

    Ravinder

    May 13, 2009 at 5:46 am

    • Yeah… It depends on http://iplocationtools.com.
      I hope service will be always available. Don’t use negative mind in every situation, only use it…
      what if when service of Google maps is not available?

      But thanks for comment…
      :)

      Santosh Wadghule

      May 16, 2009 at 7:00 pm

  2. You are right about the availability.

    You can hosted the database in your own server.

    We are using the IP2Location database from http://www.ip2location.com for local hosting and query.

    Tim

    June 1, 2009 at 7:45 am


Leave a Reply