Domanda

I have just started to make a simple socket "chat" server where users connect to my server through telnet. I was wondering how I could get the connected users IP address so that It would print out that users message like so:

IP address: "Hello"

This is the code I am using so far:

def broadcast(self, message):
      for sessions in self.sessions:
          sessions.push('>>' + message + '\r\n')

Thanks in advance, If you need any more information please ask.

EDIT:

A link to the entire program: http://pastebin.com/9vzuiLZe

È stato utile?

Soluzione 2

You should add to your code:

class ChatSession(async_chat):
    def __init__(self,server,sock):
        async_chat.__init__(self, sock)
        self.server = server
        self.set_terminator("\r\n")
        self.data = []
        self.sock = sock # <--- add this, so you remember the socket object

And then use what @staticd suggested:

def broadcast(self, line):
    for sessions in self.sessions:
        sessions.push(sessions.sock.getpeername() + ': ' + line + '\r\n')

Altri suggerimenti

<your-socket-instance>.getpeername() will give you what you want

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top