Creating a server and client with sockets

To create a socket, the socket.socket() constructor is used, which can take the family, type, and protocol as optional parameters. By default, the AF_INET family and the SOCK_STREAM type are used.

In this section, we will see how to create a couple of client and server scripts as an example.

The first thing we have to do is create a socket object for the server:

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

We now have to indicate on which port our server will listen using the bind method. For IP sockets, as in our case, the bind argument is a tuple that contains the host and the port. The host can be left empty, indicating to the method that you can use any name that is available.

Get Mastering Python for Networking and Security now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.