Python Network Programming Tutorial

Introduction:

In this instructional guide, we will explore Network Programming using Python. Python is pivotal in the realm of network programming. The standard operating system library of Python accommodates various networking concepts, including networking itself, as well as data encoding and decoding. Developing network services in Python is considerably simpler compared to utilizing C++. In this section, we will delve into the foundational aspects of Python network programming. Python offers two tiers of network access, which are -

  1. Low-Level Access:

With low-level access, you gain the ability to utilize the fundamental socket functionality provided by the operating system. This allows you to implement both clients and servers capable of handling connection-oriented as well as connectionless protocols.

  1. High-Level Access:

Utilizing the elevated access granted by Python libraries, you can interact with application-layer network protocols. These protocols include FTP, HTTP, and others.

What is a Socket?

Think about a bidirectional communication channel; the socket serves as the endpoint of this channel. These sockets are capable of facilitating communication either within processes, between processes on a single machine, or across processes on separate machines. Sockets employ various techniques to identify the type of connection for port-to-port communication that exists between the client and the server. The protocols implemented in these sockets include DNS, IP addressing, E-mail, FTP, and others.

Vocabulary of the Sockets:

The vocabulary of the socket is given below -

Terms Description of the terms
Type The communication type of the socket.
Protocol Specify the type and type of protocol used in the type. Usually, it is zero.
Domain The set of protocols used for transportation methods such as AFINET, PFINET, etc.
Port The server listens for client calls on one or more ports. The port number, service name, or Fixnum port can be a string.
Hostname Check the network interface. This can be a string containing a hostname, an IPv6 address, or a string containing both addresses. It can be an integer or a string which have zero length or a string ""

Programming of the Sockets:

Socket programming is a technique that enables two nodes within a network to exchange information. In this framework, one socket monitors a designated IP port, while another socket initiates a connection to it. When a client establishes a connection with a server, the server generates a listening socket. These components serve as the fundamental infrastructure for web browsing. To summarize, the architecture consists of a server and a client. For implementing socket programming, we utilize the socket module. Therefore, we must incorporate the socket module using the following command -

Example

import socket

To establish a socket, it is necessary to utilize the Socket.socket function.

Syntax:

The structure for socket programming is outlined as follows -

Below is an example of a Python program that demonstrates socket programming. The following code is provided for your reference -

Example

socket.socket(socket_family, socket_type, protocol=0)

Here,

  • socketfamily is either AFUNIX or AF_INET.
  • sockettype is either SOCKDGRAM or SOCK_STREAM.
  • protocol is usually left out, and its default value is 0.

Program Code:

In this section, we present a sample code for socket programming using Python. The following code illustrates the implementation -

Example

import socket

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

print("The socket is:", soc)

Output:

We will now execute the aforementioned code to retrieve the socket name from it. The resulting output is displayed below -

Example

The socket is: <socket.socket fd=624, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0>

The socket module offers a wide array of possibilities for both client-side and server-side programming. In this section, we will explore each method comprehensively.

1. Socket Server method:

This technique is implemented on the server side. Below, we will explore all the functionalities associated with this method.

Function Name Description
soc.bind() It connects the address to the socket. This address consists of a hostname and port number pair.
soc.accept() TCP accepts client connections passively and blocks them until a connection arrives.
soc.listen() It starts as a TCP listener.

2. Socket Client method:

This technique is applied on the client side. Below, we will explore all the functionalities associated with this method.

Function Name Description
soc.connect() It is used to initiate a TCP server connection.

3. Socket General method:

This section outlines the primary functionalities of the socket module in Python. We will explore each function of this module in detail below -

Function Name Description
soc.send() It is used to send the TCP message.
soc.sendto() It is used to send the UDP message.
soc.recv() It is used to receive the TCP message.
soc.recvfrom() It is used to receive the UDP message.
soc.ghostname() It is used to returns the host name.
soc.close() It is used to close all the sockets.

Server Client program in Python:

In this section, we will explore the server-client programming model using Python. We will begin by focusing on the server component -

Server:

The server includes a bind function that associates it with a specific IP address and port, enabling it to await incoming requests from that designated IP and port. Additionally, the server features a listen function that activates listening mode, permitting it to be receptive to new connections. The server's accept and close functions handle connection management. The accept function establishes the connection with the client, while the close function is responsible for terminating all connections with that client.

Program Code:

In this section, we provide the source code for server-side network programming utilizing Python. The code is presented below -

Example

# Here, we import the socket library

import socket

# Here, we create an object of socket

soc = socket.socket()

print ("The Socket is created successfully")

# Have a port on your computer; in our case, it is 50675, but it can be any port

port_no = 50675

# In addition to connecting to the port, we entered an empty string in the IP field, not an IP, which allows the server to listen for requests from other computers on the network.

soc.bind(('', port_no))

print ("The socket is binded to %s" %(port_no))

# Here we put the socket into in the listening mode

soc.listen(10)

print ("The socket is listening")

# It loops forever until we interrupt it or an error occurs

while True:

    # Here, we established a connection with the client.

    client, addr = soc.accept()

    print ('Got a connection from', addr )

    # Here, we send a thank you message to the client.

    client.send(b'Thank you for connecting with the socket')

    # Here, we close all the connections with the client

    client.close()

Output:

At this point, we will execute the code mentioned above and observe the outcome it produces. The resulting output is outlined below -

Example

The Socket is created successfully

The socket is binded to 50675

The socket is listening

Explanation:

We instantiate a socket object and assign a port number on our machine. By providing an empty string, we indicate that the server is prepared to accept connections from external computers. Conversely, if we had specified 127.0.0.1, the server would be restricted to listening solely on the local machine. Subsequently, we set the server to listening mode. In this context, the number 10 signifies that the server can queue up to 10 connections; any connection attempt beyond this limit, such as the 11th socket, will be denied. Lastly, we implement a while loop that continuously accepts incoming connections, concluding each one with a thank-you message sent to the respective connection socket.

Client:

At this point, we need to establish a means for the server to communicate with our system. We can notify this server about our operational status. Please input the subsequent command into the terminal:

Example

# Here starts the server

python server.py

# Here, keeps the above terminal open and now open another terminal and type:

telnet localhost 12345

Program Code:

In this section, we present the client-side program code for network programming implemented in Python. The code is displayed below -

Example

# Here, we import the socket library

import socket

# Here, we create an object of socket

soc = socket.socket()

# Have a port on your computer; in our case, it is 50675, but it can be any port

port_no = 50675

# Here, we connect to the server on the local computer

soc.connect(('127.0.0.4', port_no))

# Here, we received the data from the server

print(soc.recv(1024))

# Here we close all the connection

soc.close()

Output:

At this point, we will execute the code previously mentioned and observe the output it generates. The resulting output is presented below -

Example

The Socket is created successfully

The socket is binded to 50675

The socket is listening

Got a connection from ('127.0.0.4', 50675)

b'Thank you for connecting with the socket'

Explanation:

We establish a connection to localhost using port 50675 (the designated port for the server's operation), retrieve the necessary data from the server, and subsequently terminate all connections. Next, we will save this script as client.py and execute it from the terminal following the initiation of the server script.

Conclusion:

In this tutorial, we will explore Network Programming in Python and delve into the process of creating a server-client application utilizing Python.

Input Required

This code uses input(). Please provide values below: