Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the interface offering the route to a specific IP in Python3?

On a Windows machine there are different network interfaces available. One of these interfaces is the TAP interface connected to a VPN-server, with a specific IP (e.g. 10.25.1.9). To reach the host 10.2.1.1 the route leads through this interface.

I want to start a local python server program and bind it to this interface, so I need to know the IP address to bind to. Since this local server program shall be installed on several machines from which I don't know the IP addresses, I want to find this IP automagically.
It can be that there are several VPN connections installed on the machine, so neither a IP address prefix is unambiguous nor the interface name can safely assumed to be unique.

The only safe thing I know about the interface is the fact that through it the host 10.2.1.1 can be reached (probably I will test some simple service on that host to be sure that this is the right one).

I had a look at netifaces but it does not offer this. I also had a look at PyRoute2 but this is not available on Windows machines.

So, my question remains: how can I find out which interface the route to my VPN base host 10.2.1.1 leads through, so I can take this IP to bind to?

like image 375
lars k. Avatar asked Jan 27 '26 19:01

lars k.


1 Answers

Provided that there is any known service to connect to on the remote host, use socket.getsockname() to find out which local IP is used for connecting:

import socket

# connect to known destination, e.g. via UDP port 80
test_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
test_sock.connect(("10.2.1.1", 80))
# check which local IP was used to connect
with test_sock:
    private_ip, *_ = test_sock.getsockname()
like image 68
MisterMiyagi Avatar answered Jan 29 '26 13:01

MisterMiyagi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!