Over a million developers have joined DZone.

How To Get The Public Ip Address Of Current Host

·
In a virtual host, or when your application could run on a multiple type of OS,
it could be difficult to get the IP address corresponding to your default gateway.

Here a solution, which should be 'universal'.

This snippets try to send a datagramme on a distant host (no matter if datagrame
arrive), and retrieve the local IP with the return-value of the connect :


Socket.do_not_reverse_lookup=true

def get_public_ip()
  UDPSocket.open do |s|
    s.connect '208.80.152.2', 1 # wikipedia, connection don't need to be effective
    s.addr.last
  end
end


This option must be positionned :

 Socket.do_not_reverse_lookup=true

If not, your ruby machine will try to find DNS name of wikipedia, which could
take a very long time if host is isolated.



Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}