Sunday, July 19, 2015

How to determine the time zone of an IP in Ruby

In ruby / Rails, you may need to get the timezone of an ip address.

One of the best options is the Maxmind.com GeoIP . The solution provided here applies to geolocate an IP address to get the timezone, country, city etc

Local or Remote

For better results I recommend to use their web service to geolocate a city : http://dev.maxmind.com/geoip/geoip2/web-services .
The service is not free but you can pay 20$ for 50K resolutions. Fair enough.
I write a new post on how to query the web service.

Another option is to resolve the geolocation locally. Maxmind provides a free database that is updated every month. As a free product, it is less accurate than the web service but gives good results. http://dev.maxmind.com/geoip/legacy/geolite/

Local set up

We need:
- download the database
- include the `geoip` gem, that will read the database
- our code to query the geoip gem
- link back to Maxmind

Download database

Read http://dev.maxmind.com/geoip/legacy/install/city/ for instructions. It boils down to:

cd /tmp
wget -N http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
gunzip GeoLiteCity.dat.gz
mv GeoLiteCity.dat /usr/local/share/GeoIP/

I recommend you to make a bash script with these commands and run a cron once a month

Required gem


To read the legacy GeoIP database I recommend the pure ruby geoip gem. Just include in your Gemfile
 gem 'geoip'

or
 gem install geoip

Boilerplate

The interface of GeoiP gem is really simple however, as we are using a database with less than 100% accuracy, we should account for cases where timezone is not available.
When a ip resolves to a location without timezone, the best trick I found was to try with 'enclosing' networks (bigger supernets) until a result has timezone. That is: first try a perfect match, then try for the network with the last bit of the address masked, then mask 2 bits ...  https://en.wikipedia.org/wiki/Subnetwork#Subnet_and_host_counts


class Ip2Geo

  DB_PATH = '/usr/local/share/GeoIP/GeoLiteCity.dat'

  def timezone(ipv4)
    if ipv4.present?
      addr = IPAddr.new(ipv4.to_s.strip)
      32.downto(16).map do |mask| #if an address fails, test with enclosing network X.X.X.X , X.X.X.0 , X.X.0.0 ...
        network = addr.mask(mask).to_i
        c = db.city(network)
        if c && c.timezone
          return c.timezone
        end
      end
    end
    nil
  end
#a similar pattern can be re-used
  def country_code(ipv4)
    if ipv4.present?
      candidate = ipv4.to_s.strip
      addr = IPAddr.new(ipv4.to_s.strip)
      32.downto(16).map do |mask|
        network = addr.mask(mask).to_i
        c = db.city(network)
        if c && c.country_code2
          return c.country_code2
        end
      end
    end
    nil
  end

  def location(ipv4)
    if ipv4.present?
      candidate = ipv4.to_s.strip
      addr = IPAddr.new(ipv4.to_s.strip)
      32.downto(16).map do |mask|
        network = addr.mask(mask).to_i
        c = db.city(network)
        return c if c
      end
    end
    nil
  end


  def db
    @db ||= GeoIP.new(DB_PATH)
  end

end

To resolve the ip

locator = Ip2Geo.new
locator.timezone('193.110.128.199')

Attribution

Remember that the use of the free database requires an attribution: The attribution requirement may be met by including the following in all advertising and documentation mentioning features of or use of this database 
This product includes GeoLite data created by MaxMind, available from http://www.maxmind.com



19 comments:

  1. Hard Rock International - DrmCD
    Hard Rock International · 인천광역 출장샵 Founded by the late 강원도 출장안마 Steve Lukather, Hard Rock's main contribution was the discovery of a new guitar instrument 대전광역 출장샵 called the 순천 출장마사지 Signature Signature. The 익산 출장마사지

    ReplyDelete
  2. I appreciate your blog's thorough information about dedicated server hosting services. You cover dedicated hosting well. Additionally, Canada Dedicated Server Hosting offers the best information on VPS Server Hosting. Your information deserves to be valued!

    ReplyDelete
  3. These are some of the informative and unique points that you have shared. I appreciate your work. Click on our link if you want to know about our site Greece Dedicated Hosting

    ReplyDelete
  4. This knowledge is really helpful! This blog is an excellent resource for knowledge that I find to be very helpful. We appreciate you alerting us to this, so much! Ask us for more information about our services if you're seeking for the quickest and least expensive Dubai VPS Server.

    ReplyDelete
  5. Wow! You wrote a really good blog post. I truly appreciate it. This blog's information on Another Step Forward for Web Hosting Service Provider is really helpful. Ask us for additional information about our options if you're seeking for the quickest and most affordable Singapore VPS Server.

    ReplyDelete
  6. Really Very Informative Idea, beneficial for Business Needs. If you want to buy Netherlands VPS Server so Contact us now, here you will Get Cheapest VPS Server.

    ReplyDelete
  7. This article is handy! I find it to be beneficial. We appreciate you alerting us to this; thank you so much.Finland VPS Server

    ReplyDelete
  8. Your article is worth reading and informative but if you are interested to know about USA VPS Server contact us now

    ReplyDelete
  9. Great You wrote an excellent blog post. I genuinely appreciate it. This blog's information is beneficial.
    India Dedicated Server

    ReplyDelete
  10. These are some of the informative and unique points that you have shared. I appreciate your work. Click on our link if you want to know about our site India VPS Server.India VPS Server

    ReplyDelete
  11. This blog post is Nice! You wrote an excellent blog post. I genuinely appreciate it. This blog's information on Another Step Forward for Web Hosting Service Providers is valuable. Ask us for additional information about our options if you're seeking the quickest and most affordable USA VPS Server.

    ReplyDelete
  12. This article is handy! I find it to be beneficial. We appreciate you alerting us to this; thank you so much. USA VPS Server

    ReplyDelete
  13. Excellent article. This article is beneficial, and the point you made is also constructive. Please keep writing these kinds of helpful blogs. OnliveInfoech's Cloud VPS Server Hosting is very cheap if you need dedicated server hosting for your website. It comes with top-level security, high bandwidth, and many other features.

    ReplyDelete
  14. Impressive article I was searching for this type of informative content and I found it here thank you so much for sharing this. If you want to buy VPS Server So must try Turkey VPS Server.

    ReplyDelete
  15. Impressive article I was searching for this type of informative content and I found it here thank you so much for sharing this. If you want to buy VPS Server So must try UK VPS Server.

    ReplyDelete
  16. Your Blog is really very Informative and helpful for the business. Keep updating such type of information and if you want to buy Russia Dedicated Server then check out our website and get it at the lowest price.

    ReplyDelete
  17. Your Blog is worth Reading its a really very informative blog which I was Searching for a long time, If you want to know or buy Russia Dedicated Server then Purchase it now.

    ReplyDelete
  18. This comment has been removed by the author.

    ReplyDelete
  19. This comment has been removed by the author.

    ReplyDelete