Dec 26
Sometimes its nice to be able to find out what IP address you are using to get to the Internet for things like setting up servers on the correct interface. I use the following code to find this out:
#!/usr/bin/ruby
require 'open-uri'
def myINETaddr
ip1 = open("http://ip.dnsexit.com/").read[1..20]
ip2 = open("http://checkip.dyndns.org:8245/").read[/IP Address\: (.*)\<\/body/, 1]
if ip1 != ip2
throw "myINETaddr::UnableToRetrieve"
end
return ip1
end
if __FILE__ == $0
puts myINETaddr
end
I have it check two outside services just to make sure they both agree…otherwise I have it throw an error. Of course, if you are behind a proxy server or NAT device, this method is just going to return the IP address of that device. If you just want the IP address of your default network interface, this code does the job just fine:
require 'socket' def myIPaddr IPSocket.getaddress(Socket.gethostname) end if __FILE__ == $0 puts myIPaddr end






