Networking in Python

We deal with information exchange every day. We would have also come across a lot of cases where we need to set up or used a server-client connection. An example of such a case is searching for some topic on google. In this article, we will learn networking in Python, Python’s socket module, and also setting up a client-server network using the socket module. So let us start with the basics of networking.

Introduction to Networking

Networking is basically the process of two devices interacting and exchanging data. But how do the devices identify each other? The IP address (Internet Protocol address) and port number are the two things that do this job.

IP address helps in identifying the host/computer on the network and the port is used to find the application/services on the device. The IP address can be thought of as the city/town name and the port as the street address. These both are required to form the connection between the computers.

Then what are sockets? When we talk about bidirectional communication, the endpoint or the nodes are called sockets. And the information exchange can happen in any of the following ways:
1. When the process is going on
2. Between the process on same or different machines

As discussed above, we will be using the socket module to form the network. Before discussing the functions in the socket module and forming the network, let us see some important terms that we need to know in this module.

Terminology in Socket Module

We will come across the following terms while dealing with the socket module:

1. Domain:

When forming the connection, we need to mention the protocol. The domain is the set of these protocols. In Python, we have the constants to represent these protocols and these are AF_INET, PF_INET, PF_UNIX, PF_X25, and so on.

2. Type:

The communication in a network can be of two types, namely, TCP (Transmission Control Protocol) and UDP (User Datagram Protocol). TCP is connection-oriented network, where we need to first form the connection to transmit to the data. WHere as UDP is a connection-less network.

We need to mention SOC_STREAM for TCP network and SOC_DGRAM for UDP network

3. Protocol:

This term here defines the protocol used within the domain and the type. By default, it is zero.

4. Port:

As said before port is the number that identifies the service of the device. We can either give the port number, a service name, or the string of port number as the input.

5. HostName:

This is basically the IP address that identifies the device. This can be a string of hostname, the address separated by dots, or an IP6 address. This value can also be an empty string, an integer, or the word “<broadcast>”.

Methods in Python Socket Module

Done with the discussion on the vocabulary of the socket module, let us also discuss the methods.
Before starting any connection or transferring data, we need to first import the socket module. This can be done by writing the following statement.

import socket

Then we need to create the socket using the socket.socket() function.The syntax of this function is :

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

Here,
1. The scoket_family can be either AF_UNIX or AF_INET as said before.
2. The socket_type is either SOC_STREAM or SOC_DGRAM
3. The protocol is usually ignored and set as the default value, i.e.0.

Let us see an example of creating the socket.

Example of creating a socket:

import socket 
sct=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print(sct)

Output:

<socket.socket fd=1244, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0>

We can see that the details of the socket created are shown on printing the socket.

Let us now see the methods in this module. These methods can be classified into three types:

1. Methods related to the server: These are the methods used at the server’s send in the network.
2. Methods related to the client: These are used by the client while forming the connection
3. General methods: These are the methods used at both ends

Let’s see the methods under each category :

1. Socket Methods at Server’s End:

a. s.bind():

This function binds or combines the address of the socket by taking the hostname and the port as inputs.

b. s.listen():

This function sets up the TCP listener and starts it.

c. s.accept():

This function accepts the connection from the server when it arrives. It blocks or waits until the connection arrives.

2. Socket Methods at Client’s End:

a. s.connect():

This function initiates the TCP connection at the client’s end.

3. General Socket Methods:

a. s.send():

As the name shows, this function sends the TCP message.

b. s.sendto():

This is similar to the above method but is used in the UDP network.

c. s.recv():

This function is used to receive the TCP message.

d. s.recvfrom():

This function is similar to the recv() function, except that it is used in the UDP network.

e. s.close()

This function is used to close the socket to stop the connection

f. s.gethostname():

Using this function we can get the hostname.

Implementation of the network using socket

We will now see the implementation of the client-server networking using the socket module and also see the outputs on both sides.

Example of networking at server’s end:

#server end
import socket  #importing the module

sct=socket.socket() #creating the socket 
sct.bind((socket.gethostname(),9999)) #binding the IP address and the port number by passing them as elements of a tuple 
'''
Here we used 9999 as the port number. The port number can be in the range of 0 to 65535. We can use any port number that is free. 9999 is one of them. So, we used it.
'''

sct.listen(5)# This listens and waits for 5 connections. We should give any limit, here 5, as we cannot accept infinite connections
print('Waiting for connection...')

#Now for every connection we want to interact. So we will write a loop
while True:
    client,add=sct.accept() #this function accepts the connection from client and returns the client name and its address
    
    c.send(bytes('Hello! Welcome to Pythongeeks','utf-8')) #sending a TCP message to the client in the form of bytes 
    
    c_msg=sct.recv(1024).decode() #getting the TCP message from the client and decoding it 
    print(f'The message from the client {client} is {c_msg}') #printing the message
    sct.close() #This stops the connection

Example of networking at the client’s end:

#client end
import socket #importing the module

cSct=socket.socket() #creating the socket

cSct.connect((socket.gethostname(),9999)) #connecting to the server

print("The message from the server is ",cSct.recv(1024).decode())
#receiving the TCP message and printing it. Since the message is sent in bytes, we have to decode it before printing

cSct.send(bytes('Happy to connect with you!','utf-8')) #sending the TCP message to the server in bytes form

cSct.close() #This stops the connection

Other Python Internet Modules

Let us see some other internet modules in Python.

Python Module Protocol Function Port Number
httplib, urllib, xmlrpclib For HTTP protocol It deals with web pages 80
nntplib For NNTP protocol It deals with Usenet news 119
ftplib, urllib For FTP protocol It deals with the transfer of files 20
smtplib For SMTP protocol It deals with sending mails 25
poplib For POP3 protocol It is used for fetching mails 110
imaplib For IMAP4 protocol It is used for fetching mails 143
telnetlib For Telnet protocol It deals with command lines 23
gopherlib, urllib It deals with gopher protocol It deals with transferring  documents 70

Exceptions in Python Socket Module

Let us also discuss the exceptions that might be thrown while dealing with the socket module.

1. exception socket.error:

We get this when there is some problem with creating the socket.

2. exception socket.herror:

We get this error when there is some problem finding the address or any other issues related to the address.

3. exception socket.gaierror:

This is also an error related to the address.

4. exception socket.timeout:

This error pops up when the processes related to the socket take a lot of time to occur.

Conclusion

In this article, we learned a lot about networking and doing this process in Python using the socket module. We saw keywords and methods in the socket. Then we saw the implementation of client-server network. Finally, we saw some executions.

Hope you understood the discussed concepts. Happy learning.

Did you like our efforts? If Yes, please give PythonGeeks 5 Stars on Google | Facebook

3 Responses

  1. John Sanabria says:

    Greetings,

    Line 17, change ‘c.send’ by ‘client.send’
    Line 19, change ‘sct.recv’ by ‘client.recv’
    Line 21, change ‘sct’ by ‘client’

Leave a Reply

Your email address will not be published. Required fields are marked *