DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Michael has posted 7 posts at DZone. View Full User Profile

Ruby One-liner To Find External IP Address Across NAT Router.

05.02.2007
| 13899 views |
  • submit to reddit
        Sometimes you just have to know what your external IP address is when there's a NAT between you and the rest of the world.  Say you're in a DHCP environment that's constantly changing your IP, for example.  This one-liner gives you your IP address as a string (in this case stored as "my_ip").

my_ip = (require 'open-uri' ; open("http://myip.dk") { |f| /([0-9]{1,3}\.){3}[0-9]{1,3}/.match(f.read)[0].to_a[0] })
    

Comments

Evgeny Goldin replied on Fri, 2013/03/15 - 6:34am

require 'JSON';require 'open-uri';puts open( 'http://jsonip.com/ ' ){ |s| JSON::parse( s.string())['ip'] };

Martin Xu replied on Wed, 2007/05/02 - 10:27pm

how about this: {|f|f.read.scan(/([0-9]{1,3}\.){3}[0-9]{1,3}/);puts $~}

Bill Thomas replied on Thu, 2007/02/22 - 3:51pm

Wow- cool !