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

Snippets has posted 5883 posts at DZone. View Full User Profile

How To Get The Public Ip Address Of Current Host

  • submit to reddit
        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 :


def get_public_ip() do |s|
    s.connect '', 1 # wikipedia, connection don't need to be effective

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