Alireza
Alireza

Reputation: 46

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?

Upvotes: 0

Views: 12477

Answers (3)

Apoorv Gunjan Pathak
Apoorv Gunjan Pathak

Reputation: 65

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).

Upvotes: 0

MaxPowers
MaxPowers

Reputation: 5486

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.

Upvotes: 1

user14757127
user14757127

Reputation:

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.

Upvotes: 0

Related Questions