Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

socket.bind() vs socket.listen()

Tags:

python

sockets

I've learned how to write a python server, and figured out that I have a hole in my knowledge. Therefore, I would glad to know more about the differences between the commands bind(), listen() of the module called socket.

In addition, when I use bind() with a specific port as a parameter, Is the particular port being in use already, before using the listen() method?!

like image 727
Amit Gabay Avatar asked Jun 21 '26 18:06

Amit Gabay


1 Answers

I found a tutorial which explains in detail:

... bind() is used to associate the socket with the server address.

Calling listen() puts the socket into server mode, and accept() waits for an incoming connection.

listen() is what differentiates a server socket from a client.


Once bind() is called, the port is now reserved and cannot be used again until either the program ends or the close() method is called on the socket.

A test program that demonstrates this is as follows:

import socket
import time

HOST = '127.0.0.1'
PORT = 65432

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
while 1:
    time.sleep(1)

when running two instances of this program at once, you can see that the one started last has the error:

Error image

Which proves that the port is reserved before listen() is ever called.

like image 124
nicholas Avatar answered Jun 23 '26 07:06

nicholas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!