python socket.connect 似乎不适用于虚拟 IP

标签 python linux networking

我已经通过以下方式设置了一些虚拟 IP:

~# ip link add link eth0 name eth0.1 address 11:22:33:44:55:66 type macvlan
~# ifconfig eth0.1 10.10.0.0/24

我正在使用以下代码进行连接:

sTCP = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sTCP.setsockopt(socket.SOL_SOCKET, IN.SO_BINDTODEVICE, IFACE)
print "PORT s_TCP:" + str(HOST) +":" +str(TCP_PORT)
sTCP.connect((HOST, TCP_PORT))
print "Connected"

如果 IFACE 是 eth0,这可以正常工作,但它不会从 eth0.1 通过 sTCP.connect 并且在 eth0.2 上的 bindtodevice 中失败(如预期的那样)。

为什么 eth0.1 不工作?这是 python 问题,还是 linux 网络实现中的问题?

最佳答案

我刚刚在我的 Fedora 13 系统上尝试了这个并且它有效。我确实必须进行一些修改才能使其在我的系统上运行,希望这能为您提供线索。使用的代码:

### in shell
# Used 00 for first MAC octet to avoid issues with multicast addressing
ip link add link eth0 name eth0.1 address 00:22:33:44:55:66 type macvlan
ifconfig eth0.1 10.1.23.6/25

# python
import socket
HOST = "10.1.23.30"
TCP_PORT = 80
IFACE = "eth0.1"
sTCP = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# switched to socket.SO_BINDTODEVICE since I'm not sure what "IN" referred to
# EDIT: figured out there's another module called IN, but the value is the same (25)
sTCP.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, IFACE)
print "PORT s_TCP:" + str(HOST) +":" +str(TCP_PORT)
sTCP.connect((HOST, TCP_PORT))
print "Connected"

我使用 tcpdump 向自己证明数据包来自 eth0.1。也许您遇到了 VLAN 问题?在客户端和服务器上运行数据包捕获以查看线路上实际发生的情况。

关于python socket.connect 似乎不适用于虚拟 IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7376024/

相关文章:

python - f2py:预分配数组作为 Fortran 子例程的输入

c++ - 使用 Monit 监控 C++ 多线程进程

Linux 内核设备驱动程序需要访问用户空间中的共享对象

linux - 如何使用 linux shell 脚本更改文件中的单词

powershell - Azure Powershell - 如何更改网络子网

azure - 有没有办法像网站一样向公众共享 Azure VM 上的文件夹?

python - 即使 DAG 未运行, Airflow 变量也会更新

python - 如何对具有多索引的时间序列进行滚动窗口计数?

python - 如何使用 Django 检索模型字段的值分布?

java - 如何从 Android 应用程序检测 WiFi 网络中连接的所有设备