Socket

Contents

Socket#

A socket interface is a programming construct that enables communication between two devices or processes over a network. It serves as an endpoint for transmitting and receiving data across the network. Python provides a dedicated library called socket that allows you to utilize sockets for your specific needs.

import socket

Listening#

In the following example we creating socket, binding it to the all awailable networkinterfaces and port 5000 and make it to listen.

server_socket = socket.socket()
server_socket.bind(("0.0.0.0", 5000))
server_socket.listen(1)

Now if you check the processes that occupy port 5000 - there is indeed a python3 process there.

!lsof -i :5000
COMMAND    PID                 USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
python3 227872 f.kobak@maxbit.local   67u  IPv4 718964      0t0  TCP *:5000 (LISTEN)

Next cell closes socket.

server_socket.close()

As a result, there won’t be any processes using port 5000.

!lsof -i :5000