Say a multi-horned PC has two network interface with IP address 192.168.1.100/24 and 192.168.2.100/24. If any other PC send a multicast message to any of them, I need to send a response back, but in the UDP data part of the response, I need to tell that PC my proper IP address which they can reach.
Say 192.168.1.123 send that multicast message, I can use ip route get to 192.168.1.123
to determine which one is the proper interface to use(which is 192.168.1.100), but I don't know how to do this in ruby code.
To invoke external process then parse the stdout is not what I want, cause it's too slow for a busy network, and to make it cross-platform is not that easy.
Currently I mimic the route resolving with these codes:
localifs = Socket.ip_address_list.keep_if { |addr| addr.ipv4? and not(addr.ipv4_loopback?) }
raise Error, "There is no alive ipv4 interface on local machine" if localifs.empty?
src_addr_i = IPAddr.new(src_addr).to_i
localifs = localifs.sort do |x,y|
(IPAddr.new(x.ip_address).to_i ^ src_addr_i) <=> (IPAddr.new(y.ip_address).to_i ^ src_addr_i)
end
host = localifs.first.ip_address