如何创建到特定网络接口的传出套接字? [英] How do I make an outgoing socket to a SPECIFIC network interface?
问题描述
我的服务器有两个不同的网络接口,每个接口都有不同的 IP 地址.我怎样才能创建一个套接字,让它从特定的 IP 地址出去?
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?
我更喜欢 Python 的例子,但问题是语言不可知的,所以请远离.
I'd prefer a python example, but the question is language agnostic, so shoot away.
请不要给我你不能"作为答案.我的意思是,它是一台电脑.例如,我可以做任何我喜欢的事情——我可以通过编程方式禁用一个我不想要的界面.我正在寻找更漂亮的东西.
Please don't give me "You can't" as an answer. I mean, it is a computer. I can do anything I like to it, for example - I can programatically disable the one interface I don't want on the fly. I'm looking for something prettier.
推荐答案
您当然可以将套接字绑定到特定设备.
You can certainly bind a socket to a specific device.
我不知道如何在 python 中执行此操作,但是使用 berkeley socket api(在 C 中)您需要调用 setsockopt()
,使用选项 SO_BINDTODEVICE
>.
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
.
您传入一个接口描述符,其类型为 struct ifreq
.理想情况下,您可以使用 ioctl()
获取接口描述符的内容,并请求 SIOCGIFINDEX
- 将接口名称(例如 eth0)作为参数传递.
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.
刚刚快速搜索并找到this 中套接字方法的文档Python.setsockopt()
就是其中之一.
edit: Just did a quick search and found this documentation of the socket methods in python. setsockopt()
is amongst them.
这篇关于如何创建到特定网络接口的传出套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!