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
Ruby One-liner To Find External IP Address Across NAT Router.
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 - 7: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 - 11:27pm
{|f|f.read.scan(/([0-9]{1,3}\.){3}[0-9]{1,3}/);puts $~}Bill Thomas replied on Thu, 2007/02/22 - 4:51pm