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

Question:

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?

Asked By: Alireza

||

Answers:

The script does not answer this by itself, however, I assume laddr=(‘127.0.0.1’, 9999) is the listening address of the server-side app. That’s where connections are established. the raddr is the connection port the request comes from. When you listen to a port with a server, the client uses any non-reserved port >1024 to connect to the server and this is totally random, as long as it is defined in the client-app.

So you have to different connection points for one established connection. The one port and address as the sender-side (described as raddr) and the one as the receiver side (here described as laddr – for listen)

That’s basically the logic behind any TCP-related connection.

Answered By: user14757127

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.

Answered By: MaxPowers

accept() function returns a socket descriptor that is connected to your TCP server. In this case, it returns a tuple of objects.

The first parameter, conn, is a socket object that you can use to send data to and receive data from the client that is connected.

The second parameter, addr, contains address information about the client that is connected(e.g., IP address and remote part).

Answered By: Apoorv Pathak

A server has a bind() method which binds it to a specific IP and port so that it can listen to incoming requests on that IP and port

Answered By: Shubham