如何为EXECIFIC网络接口创建传出套接字? [英] How do I make an outgoing socket to a SPECIFIC network interface?

查看:260
本文介绍了如何为EXECIFIC网络接口创建传出套接字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的服务器有两个不同的网络接口,每个接口都有不同的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.

编辑:刚做了快速搜索,发现这篇关于python中套接字方法的文档。 setsockopt()就在其中。

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

这篇关于如何为EXECIFIC网络接口创建传出套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆