[ACCEPTED]-How do I make an outgoing socket to a SPECIFIC network interface?-ip

Accepted answer
Score: 15

You can certainly bind a socket to a specific 11 device.

I don't know how to do it in python, but 10 using the berkeley socket api (in C) you 9 need to call setsockopt(), using the option SO_BINDTODEVICE.

You pass 8 in an interface descriptor, which is of 7 type struct ifreq. Ideally you would get the contents 6 of the interface descriptor by using ioctl(), and 5 requesting SIOCGIFINDEX - passing the name of the interface 4 (eg. eth0) as an argument.

edit: Just did 3 a quick search and found this documentation 2 of the socket methods in python. setsockopt() is amongst 1 them.

Score: 15

Just a little note - what I really needed 4 is to bind to a specific IP, and just for 3 the sake of completeness, the solution is 2 to bind the socket after creation. Source 1 in python:

import socket
s = socket.socket()
s.bind(("", 0))
s.connect(("321.12.131.432", 80))
Score: 1
import socket
s = socket.socket()
s.bind((get_ip_address('eth0'), 0))

from Quora


More Related questions