Hi, i'm searching for a way to know the hostname of a machine connected to my twisted-server.
I use to know the host the method self.transport.getPeer().host, and i have the IP in this way.
But i need to know the hostname. I'm searching for a way like socket.gethostname().

Waiting your answer :D

Dani AI

Generated

Short answer: self.transport.getPeer() gives you an address object (an IPv4Address/IPv6Address) whose host attribute is the remote IP — Twisted does not automatically give you a resolved hostname for that peer. (docs.twistedmatrix.com)

Recommended options (pick one):

  • Use Twisted’s asynchronous DNS client (twisted.names) to perform a PTR lookup (reverse DNS). This is non‑blocking and returns a Deferred you can attach callbacks to; it’s the Twisted‑native way to ask DNS “what name maps to this IP?”. (docs.twistedmatrix.com)

  • If you prefer the system resolver (e.g. socket.gethostbyaddr) you must not call it directly in connectionMade because it blocks the reactor. Run it in a thread with threads.deferToThread and handle failures/timeout there, then receive the result via a Deferred callback. (docs.python.org)

Practical notes and pitfalls:

  • Reverse DNS often isn’t configured on LAN hosts (so lookups can fail or return the IP). Always have a fallback to the raw IP.
  • Don’t rely on methods like getDestination() — Twisted transports expose getPeer() and getHost(); getPeer() is the remote endpoint and getHost() is the local endpoint. That resolves the AttributeError you saw when trying non‑existent methods. (docs.twistedmatrix.com)
  • If you expect many simultaneous resolves, prefer twisted.names (scales better) or tune the reactor thread pool rather than spawning unbounded threads. (docs.twistedmatrix.com)

Example patterns (concepts only — adapt to your protocol):

  • Asynchronous DNS (returns Deferred): call client.lookupPointer(reverseName(ip)) and extract the PTR answer in your callback. (docs.twistedmatrix.com)
  • System resolver off the reactor thread: threads.deferToThread(lambda: socket.gethostbyaddr(ip)[0]) and then addCallback to receive the hostname. (docs.python.org)

Context for the thread of posts: was correct to use self.transport.getPeer().host to obtain the IP; ’s suggestion of getDestination() isn’t present on the IPv4Address/transport objects — use getPeer()/getHost() and then perform a reverse lookup as shown above. (docs.twistedmatrix.com)

Recommended Answers

All 13 Replies

Something like...

self.transport.getDestination()

Cheers and Happy coding

self.nick = self.transport.getDestination()
exceptions.AttributeError: 'Server' object has no attribute 'getDestination

How about showing some code??

Anyway the getDestination() should retrieve you the hostname.

Try something like...

peer = self.transport.getPeer()
nick = peer.getDestination()

Cheers and Happy coding

Nothing to do, always the same error:

File "Server.py", line 21, in name
    self.nick = peer.getDestination()
exceptions.AttributeError: 'IPv4Address' object has no attribute 'getDestination

This is the source:

And like this?

def name(self):
    connector = self.transport.connector
    return connector.getDestination()

I'll install twisted to take a look.

Cheers and Happy coding

File "Server.py", line 20, in name
    connector = self.transport.connector
exceptions.AttributeError: 'Server' object has no attribute 'connector'

=(

I've installed twisted mate.

Do you have client code? Can you post it, or PM it to me?

Cheers and Happy coding

The client is telnet :D
But, i don't think that client is the reason. This method getDestination() doesn't exist in accordance with the interpreter's error.

Wait, this is the server code, right?

How do you connect to it?

Cheers and Happy coding

By telnet

Sorry mate, now I got it! :D

I made consfusion, the country I'm in now has a provider named 'Telnet', and I just stupidlly thought you were talking about it. I'm very sorry.

I'll take a look.

Cheers and Happy coding

Lol, no problem man, i'll wait :)

I'm new ot twisted, but thats all I was able by now to extract as peer info.

But, your implementation does'nt seem right to me.

I'll take a look into twisted, I think I'll write something, meanwhile...

from twisted.protocols.basic import LineOnlyReceiver
from twisted.internet  import reactor
from twisted.internet.protocol import ServerFactory
import time


class ChatConnection(LineOnlyReceiver):

    def __init__(self):
        self.hostlist = []
        self.hostname = ""
        self.master = ""

    def sendLine(self, line):
        self.transport.write(line + '\n')

    def print_time(self):
        return time.strftime("[%H:%M] ", time.localtime(time.time()))

    def name(self):
        self.nick = self.transport.getPeer()
        return ' '.join([str(item) for item in self.nick])
    
    def connectionMade(self):
        print  self.print_time() + "New connection from " + self.name()
    
        if self.name == self.hostname:
            self.master = self.transport.getPeer().host
        else:
            self.factory.IDandIP[self.name] = self.transport.getPeer().host
            self.hostlist.append(self.name())

        def connectionLost(self, reason):
            print self.print_time() + "Connection lost by", self.name()
            del self.factory.IDandIP[self.name]
            self.hostlist.remove(self.name())

          
        def lineReceived(self, line):
        
            if line == "/list":
                self.sendLine(self.print_time() + "Online users: \n\t" + str(self.hostlist))
    
            if line[:6] == "zombie":
                self.master.sendLine(line[:6])
            else:
                ID = line.split(" : ")[0]
        
                if ID in self.hostlist:
                      self.IDandIP[ID].sendLine(line)
        
                 
class Chat(ServerFactory):
     
    protocol = ChatConnection
    
    def __init__(self):
        
        self.IDandIP = {}

print "Waiting connection from clients..."
main = Chat()
reactor.listenTCP(8000, main)
reactor.run()

Cheers and Happy coding

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.