2

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

DeanMWake
  • 893
  • 3
  • 19
  • 38

2 Answers2

4

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

Darren Ringer
  • 278
  • 3
  • 12
staticd
  • 1,194
  • 9
  • 13
  • 1
    Thanks, although this throws an exception: 'module' object has no attribute 'getpeername' – DeanMWake Sep 06 '13 at 11:50
  • @DeanMWake not to be called on the module named `socket`, but on the actual socket which holds the connection (I know that the comment is old, but it had one upvote which is a problem). – Daniel F Aug 21 '18 at 08:09
3

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')
Ofir Israel
  • 3,785
  • 2
  • 15
  • 13
  • Thanks, problem is Im getting this exception now: can only concatenate tuple (not "str") to tuple because the peername is displayed as (ip, socket) the , is causing errors. Think I could just use regex to extract just the ip – DeanMWake Sep 06 '13 at 14:22
  • Use `sessions.push(sessions.sock.getpeername()[0] + ': ' + line + '\r\n')` perhaps? – Ofir Israel Sep 06 '13 at 14:26
  • As I said I am still a novice. I just used the tuple as if it were an array and user = sessions.sock.getpeername(); ip = user[0] :) This worked thanks – DeanMWake Sep 06 '13 at 14:31