0

From the python library 'socket' is there a method that returns the IP of the socket that got binded to it?

Suppose a socket was declared and initialized like:

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.connect(ip, port)

And I wanted to find the IP of a received datagram from a socket:

while True:
  for s in socks:
    recv = s.recv(1024)
    #get ip of s or socket
    #print received data from s.gethostname()

How would I go on about this?

Jebathon
  • 4,310
  • 14
  • 57
  • 108

3 Answers3

1

you can try with recvfrom this method returns data and the address of the sender

data, address = sock.recvfrom(4)
0

Try with socket.getpeername().

martriay
  • 5,632
  • 3
  • 29
  • 39
0

Simple way would be like

data, (ip, port) = sock.recvfrom(4096)
print (ip)
Muthukumar Anbalagan
  • 1,138
  • 12
  • 15