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
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?
Addrinfo#ipv6?
Addrinfo#ipv4_private?
Addrinfo#ipv4_loopback?
Addrinfo#ipv4_multicast?
Addrinfo#ip_address
as in:
def all_my_ipv4_interfaces
def my_loopback_ipv4
def my_first_private_ipv4
def my_first_public_ipv4
socket.ip_address_list.select{|intf| intf.ipv4?}
enddef my_loopback_ipv4
socket.ip_address_list.detect{|intf| intf.ipv4_loopback?}
enddef my_first_private_ipv4
socket.ip_address_list.detect{|intf| intf.ipv4_private?}
enddef my_first_public_ipv4
socket.ip_address_list.detect{|intf| intf.ipv4? and !intf.ipv4_loopback? and !intf.ipv4_multicast? and !intf.ipv4_private?}
endall_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 :)