Obtaining the IP address of an interface that has a route to a given host

I am writing a simple message queue library that will allow you to configure a messaging service between two servers over TCP or UDP. I want to do away with the notion of client / server, since the two servers will do the same (send and receive messages), so it doesn't matter which.

I thought I'd do this using the IP addresses of the two servers to decide which one should bind the server socket and which one should connect as a client (perhaps choosing the one with the smallest non-equal octet would be the server, assuming it is not the same computer).

To do this, I need to know the local IP address [es] of interface [s], which has a route to another computer. Is there an easy way to get this information?

+3


source to share


2 answers


$ ip route get 2a00:1450:4016:800::1011
2a00:1450:4016:800::1011 from :: via 2a01:4f8:100:63e0::1
    dev eth0  src 2a01:4f8:100:6fab:cdef::1  metric 0 

      



iproute internally uses the netlink RTM_GETROUTE message to get information, and so can you. Then src specifies the address that will be used to communicate with this node if you must use auto-bind (that is, do not call bind (2) before connecting, or invoke wildcard bind on the address field).

+2


source


perhaps choosing the one with the smallest non-equal octet server, assuming it is not the same computer



Pretty ad-hoc solution. I would use multicast on my server, and recently started looking for these multicasts and started myself as a server if I didn't find them, and advertised myself through multicasts and so on ...

+1


source







All Articles