python - 使用 IPv6 的扭曲连接 TCP
问题描述
如何使用 twisted 和 listenTCP 访问 IPv6 地址?如果我从 ifconfig 中获取地址,例如 aaa::bbbb:cccc:dddd:eeee,则会收到以下错误消息:
raise CannotListenError(self.interface, self.port, le)
twisted.internet.error.CannotListenError: Couldn't listen on aaa::bbbb:cccc:dddd:eeee
解决方案
要么endpoints.serverFromString
指定 IPv6 接口值,要么显式调用endpoints.TCP6ServerEndpoint
.
from twisted.internet import endpoints, protocol, reactor
class Echo(protocol.Protocol):
def connectionMade(self):
print(f"{type(self.transport)}")
def dataReceived(self, data):
self.transport.write(data)
# Use one of the following
# Server string, note the backslashes
tcp6 = endpoints.serverFromString(reactor, "tcp:8000:interface=\:\:1")
# Or explicit IPv6 endpoint
tcp6 = endpoints.TCP6ServerEndpoint(reactor, 8000, interface="::1")
factory = protocol.Factory.forProtocol(Echo)
tcp6.listen(factory)
reactor.run()
如果这不起作用,那么您可能需要确保在您的系统上启用了 IPv6。