Reputation: 5238
How do I know which interface will be used for a specific remote address?
Say, I have two interfaces. One of them is 192.168.0.50/24, the other is 10.0.2.30/21 and all traffic is routed through it. So, for 192.168.0.100 I expect 192.168.0.50, for 10.0.3.40 or 8.8.8.8 I expect 10.0.2.30.
I'd like to ask the OS, as it somehow binds the address to a specific interface when I do socket.connect
or socket.sendto
. So how do I find out the address the OS would bind the socket on socket.connect
without doing socket.connect
?
There are two goals: to "test" the routing table and to bind socket to a specific port and the adapter that is accessible by the peer.
Unlike in Can Python select what network adapter when opening a socket?, I don't have adapters with overlapping addresses and I don't know the address of the adapter that socket would be bound to. My goal is to find this address.
Upvotes: 1
Views: 704
Reputation: 12205
There is no out of the box way to mock a routing call as such. If you do not want to connect, you must do something to parse the local routing table information.
If you are using Linux, you can do this with pyroute2
(pip install...). It is a helper library to read and modify the routing table.
Then you could do something like this - the output requires some parsing:
from pyroute2 import IPRoute
foo = IPRoute()
bar = foo.route('get', dst='192.168.42.42')
print(bar[0]['attrs'])
The result is a tuple. You will be interested in RTA_PREFSRC
field as it will be the ip address of the local interface that would be used to route packets to that particular destination if they were to be sent.
Upvotes: 2