How to get the original TCP connection hostname in Python Twisted?
With Twisted's TCP mechanisms, when a protocol is created, the only information about the peer is its IP address and port. How can I retrieve the original hostname that I tried to connect with?
reactor.connectTCP('somehost.com', 80, MyFactory)
How can I ever get 'somehost.com'
through a callback somehow? I开发者_运维百科n other words, connectTCP
returns an IConnector
(whatever it does) - how do I correspond this to something tangible in a callback, since no deferreds are used?
Jerub's answer makes sense semantically. After digging through Twisted code, there is a more expedient and direct way of doing specifically what I'm trying to achieve.
In protocol:
def connectionMade(self):
# This is the original connector that connectTCP returned
connector = self.transport.connector
# This is the original destination requested
connector.getDestination()
The simple answer is, "Record it yourself".
Updating your example:
myfactory = MyFactory(connecthost='somehost.com')
reactor.connectTCP(myfactory.connecthost, 80, myfactory)
If it's an important piece of information, you should be explicitly passing it around explicitly, in much the same way as you would pass around details about why you connected to a host and what to do once a connection is established.
精彩评论