Can Python select what network adapter when opening a socket?

I can’t speak much for Windows, but on Linux the interface is normally not chosen until a routing decision is made, therefore you usually don’t have a say on which interface your packets leave.

You do have the option though, of using SO_BINDTODEVICE (see man 7 socket) on Linux. This binds a socket to a device, however, only root can set this option on a socket.


Just checked, and the python socket library doesn’t have SO_BINDTODEVICE defined, but you get it from socket.h:

# from socket.h
# define SO_BINDTODEVICE 25

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, 25, 'eth0')

See also:

Leave a Comment