Get public (remote) IP address

Akamai provides a "What is my IP" page that you can fetch:

require 'open-uri'
remote_ip = open('http://whatismyip.akamai.com').read

There are a few alternatives that do the same thing, though:

  • http://whatismyip.akamai.com
  • http://ipecho.net/plain
  • http://icanhazip.com
  • http://ident.me
  • http://bot.whatismyipaddress.com

You can also use the ipv4 and ipv6 subdomains with icanhazip.com.

If you don't want to depend on a third party, you can roll your own in a one-line rack app and deploy this for free on Heroku or whatever. It takes into account that X-Forwarded-For may contain a comma separated list of proxy IP addresses and only returns the client IP.

# config.ru

run lambda { |env|
  remote_ip = env['HTTP_X_FORWARDED_FOR'] || env['REMOTE_ADDR']
  remote_ip = remote_ip.scan(/[\d.]+/).first
  [200, {'Content-Type'=>'text/plain'}, [remote_ip]] 
}

I use curl:

my_ip = `curl http://ipecho.net/plain`

This does not use Ruby stdlib and requires curl though.


No scraping necessary!

I use ipify, an open api that returns your public ip address. Useful if you want a json response (not shown here).

require 'net/http'
public_ip = Net::HTTP.get URI "https://api.ipify.org"
=> "12.34.56.78" 

Or with curl:

public_ip = `curl https://api.ipify.org`
=> "12.34.56.78"

Don't get excited, that's not my public ip address :)

Tags:

Ruby