Getting a user country name from originating IP address with Ruby on Rails

前端 未结 11 1683
一整个雨季
一整个雨季 2020-12-04 08:26

I want to extract a user country name from visitors\' IP addresses.

I could get the IP address with remote_ip. But what could be the easiest way to get

11条回答
  •  我在风中等你
    2020-12-04 08:45

    The geoip gem no longer works with the new MaxMind databases. There is a new gem that does this, MaxMind-DB-Reader-ruby.

    Simply download the City or Country binary, gzipped databases from MaxMind, unzip, and use the following sort of code:

    require 'maxmind/db'
    
    reader = MaxMind::DB.new('GeoIP2-City.mmdb', mode: MaxMind::DB::MODE_MEMORY)
    
    # you probably want to replace 1.1.1.1 with  request.remote_ip
    # or request.env['HTTP_X_FORWARDED_FOR']
    ip_addr = '1.1.1.1'
    record = reader.get(ip_addr)
    if record.nil?
      puts '#{ip_addr} was not found in the database'
    else
      puts record['country']['iso_code']
      puts record['country']['names']['en']
    end
    
    reader.close
    

    Adapt based on your needs. I created a method in an initializer which I can call as necessary.

提交回复
热议问题