Search code examples
pythonpython-2.7socketserverpython-sockets

socket server - getting a connected user's ip


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


Solution

  • 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')