使用 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

解决方法

指定 IPv6 接口值或显式调用 endpoints.serverFromStringendpoints.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。