我已经通过以下方式设置了一些虚拟 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/