This came up from someone’s question on IRC. Here’s a simple way to get your local IP address in Ruby without spawning a shell and without making a connection.
require 'socket' def local_ip orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily UDPSocket.open do |s| s.connect '220.127.116.11', 1 s.addr.last end ensure Socket.do_not_reverse_lookup = orig end # irb:0> local_ip # => "192.168.0.127"
The above code does NOT make a connection or send any packets (to 18.104.22.168 which is google). Since UDP is a stateless protocol connect() merely makes a system call which figures out how to route the packets based on the address and what interface (and therefore IP address) it should bind to. addr() returns an array containing the family (AF_INET), local port, and local address (which is what we want) of the socket.
This is a good alternative to `ifconfig`/`ipconfig` solutions because it doesn’t spawn a shell and it works the same on all systems.
Anyone know a better way?