pythonpython-3.xsocketsnetwork-programmingpython-sockets

What is `conn, addr = s.accept()` in python socket?


I searched documentations and tutorials but no one talked about this, for example this is server script

import socket
 
server = socket.socket()
print("socket created")

server.bind(("localhost", 9999))
server.listen(3)
print("waiting for connection")

while True:
    client, addr = server.accept()
    print(client)
    print(addr)
    
    name = client.recv(1024).decode()
    print("connected with", addr, client, name)
    
    client.send(b"welcome bro")       
    client.close()

 

When printing client, I get this:

proto=0, laddr=('127.0.0.1', 9999), raddr=('127.0.0.1', 36182)

And addr variable :

('127.0.0.1', 36182)

Why these two variable defined by one and got two different output?

What is the logic behind scene?


Solution

  • From the documentation of the socked module:

    socket.accept()

    Accept a connection. The socket must be bound to an address and listening for connections. The return value is a pair (conn, address) where conn is a new socket object usable to send and receive data on the connection, and address is the address bound to the socket on the other end of the connection.