[Twisted-Python] pb server how to get client IP address

Brian Warner warner at lothar.com
Fri Feb 13 16:45:34 EST 2004

Martin Stenhård <stenis at stenhard.net> writes:
> I have a question on how to get ip address of the clients that connects to
> the server.

From the Protocol object, the .transport offers a pair of methods called
getHost() and getPeer(). So something like this should work:

==== BEGIN
from twisted.internet import reactor, protocol

class MyProtocol(protocol.Protocol):
    def connectionMade(self):
        print "connection from", self.transport.getPeer()

f = protocol.ServerFactory()
f.protocol = MyProtocol
reactor.listenTCP(9111, f)
==== END

When I run this on my system, and connect with 'nc localhost 9111', I get:
  % /tmp/p.py 
  connection from ('INET', '', 38002)

The value it returns depends upon the kind of transport, but TCP connections
will give you a tuple of ('INET', hostname, port), where 'hostname' is a
dotted-quad IP address.

I'll add this to the FAQ.


More information about the Twisted-Python mailing list