How do I make an outgoing socket to a SPECIFIC network interface?

前端 未结 3 2006
醉酒成梦
醉酒成梦 2020-12-08 07:35

I have a server with two different network interfaces, each with a different IP address. How can I create a socket so it\'ll go out a specific IP address?

I\'d prefe

相关标签:
3条回答
  • 2020-12-08 08:14

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

    import socket
    s = socket.socket()
    s.bind(("127.0.0.1", 0))
    s.connect(("321.12.131.432", 80))
    
    0 讨论(0)
  • 2020-12-08 08:18

    You can certainly bind a socket to a specific device.

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

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


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

    0 讨论(0)
  • 2020-12-08 08:29
    import socket
    s = socket.socket()
    s.bind((get_ip_address('eth0'), 0))
    

    from Quora

    0 讨论(0)
提交回复
热议问题