Search My Blog

ruby (4) web (4) ruby on rails (3) security (3) GPG (2) OpenPGP (2) RFC (2) linux (2) rails (2) shell (2) sysadmin (2) Exchange (1) GIT. (1) IMAP (1) RCS (1) SSH (1) SVN (1) bundle (1) cURL (1) command line (1) crack (1) css (1) developer (1) email (1) fail (1) hack (1) http (1) mac (1) network (1) password (1) regular expression (1) script (1) subversion (1) terminal (1) textmate (1) tip (1) vim (1)

Tuesday, October 25, 2011

Ruby how to get my private and public IP address



Ok,
you've just deployed your newest ruby app on a bunch of servers, and you need that this app knows the IP address of the server where it's running.

I've read some bizarre ways ("Get your local IP address" or "Get your local IP address") to do this, such as opening an UDP socket and inferring it from the interface used to route the packet.
With the Socket class you may do this more easily and also get the benefit of having useful Addrinfo objects and you are able to distinguish easily between public and private interfaces.

First of all:
Socket::ip_address_list
returns the Array of Addrinfo objects with all your interfaces (it deals with both IPv4 and IPv6).

You can then filter them using the standard Enumerable methods select() and detect() along with these Addrinfo methods:
Addrinfo#ipv4?
Addrinfo#ipv6?
Addrinfo#ipv4_private?
Addrinfo#ipv4_loopback?
Addrinfo#ipv4_multicast?
and convert them to string in dotted notation with
Addrinfo#ip_address

as in:

def all_my_ipv4_interfaces
socket.ip_address_list.select{|intf| intf.ipv4?}
end

def my_loopback_ipv4
socket.ip_address_list.detect{|intf| intf.ipv4_loopback?}
end

def my_first_private_ipv4
socket.ip_address_list.detect{|intf| intf.ipv4_private?}
end

def my_first_public_ipv4
socket.ip_address_list.detect{|intf| intf.ipv4? and !intf.ipv4_loopback? and !intf.ipv4_multicast? and !intf.ipv4_private?}
end

all_my_ipv4_interfaces
=> [#<Addrinfo: 127.0.0.1>, #<Addrinfo: 10.212.142.73>, #<Addrinfo: 62.127.4.80>]
my_first_private_ipv4
=> #<Addrinfo: 10.212.142.73>
my_first_public_ipv4.ip_address
=> "62.127.4.80"

No comments:

Post a Comment

If you find this useful please leave a feedback :)