lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Sun, Jan 12, 2014 at 02:47:48PM -0800, Paul K wrote:
> Hi All,
> 
> I've been using socket.dns.toip(socket.dns.gethostname()) to get the
> IP address of the computer my application is running on but came
> across several situations when the hostname doesn't resolve. It's
> possible to configure it manually, but I'd prefer to have a way to
> enumerate all known IP addresses and pick those that match some
> conditions I'm interested in (for example, first ip4 non-loopback
> address).

The canonical way to do this is to create and bind a socket to a known
public address, such as 8.8.8.8 (Google's public DNS service) and then call
getsockname to get the local IP. You don't even need to connect the socket.
The socket bind will force the kernel to resolve the proper local address
according to its routing table.

It's the best technique available without actually enumerating the routes in
the routing table.