How to bind a raw socket to a specific interface u

2019-09-17 01:37发布

问题:

How to bind a raw socket to a specific interface using python in linux centOS? I have multiple interfaces like eth0, eth0:1, eth0:2,etc

回答1:

You can do it by using the IP address that corresponds to the desired interface.

import socket

s = socket.socket()
s.bind(('192.168.1.100', 12345))

s = socket.socket()
s.bind(('localhost', 12345))

s = socket.socket()
s.bind(('0.0.0.0', 12345))

The first two above would bind to the interface with that IP address. The last one will bind to any interface. You can obtain the IP address for an interface using this recipe.