1

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
tsingakbar
  • 197
  • 1
  • 6
  • (I know this is old but, I have to ask) Why do you need to determine the interface? Unless you are sending the response via multicast (why would you do that?)... BTW creating a UDP socket to see where the route would go without sending anything on that socket is a good way to start (then you can examine the local address] – nhed May 30 '14 at 18:24
  • @nhed If I remember it right, at that time I was writing something to do with SSDP/UPnP protocol. For SSDP device, it needs to response to discovery multicasts with its IP address in a xml, so it is a must to use the IP address which they can really reach. I know this is absurd, 'cause they can actually get the right IP address from the message's IP layer, but this is just how it goes in the protocol. As for the method using a UDP socket without sending anything you mentioned, would you pls provide a more detailed example? – tsingakbar Jan 12 '15 at 07:31
  • OK, yes, if you use multicast (as I mentioned) you would need that, for anything else just creation of the udp socket would cause route resolution. Unfortunatly all the code I had handy for such activity in ruby, bash & C is no longer in my possesion, but I think it went something like this: http://stackoverflow.com/a/5029852/6529041 – nhed Jan 12 '15 at 15:15
  • 1
    @nhed Looks promising, thanks. – tsingakbar Jan 14 '15 at 04:25

0 Answers0