In Python, we can create applications which can run on a simple machine. But also we can develop applications that we can execute them over the network. Python networking provides different facilities to program the web.
In Python, we can write codes for the network to transfer the data. We can also write code for sockets, simple server and also for the client machine.
Working with Sockets in Python
Before we start coding the sockets in Python, we shall learn some basics such as what it is actually.
A socket in a network is simply an end point. It acts as an endpoint for the different two way directional communications channels. The Sockets provide communication within a process as well as between processes on the same machine. It can also communicate between processes of the device from the different continents.
We can implement sockets over some different channel types. The channels forms can be such as TCP, UDP, Unix domain sockets, and much more.
In Python, we have the socket library to use in our program. This library provides various classes, functions, and modules to handle the standard transports and also we can provide a generic interface for managing the rest.
Terminologies for sockets
When we start the programming for sockets in Python, there are some important terms we should be familiar. They are as follow
Between two points the type will categorize the what kind of communication will take place between them. For connectionless protocols we have SOCK_DGRAM, and for connection-oriented protocols, we have SOCK_STREAM type.
To identify what sort of protocol we will use within a domain and communication type over the network. The protocol can be such as HTTP, SMPT, POST and other.
The domain is for transporting data using the protocols over the network. We have different values such as AF_INET, PF_INET, PF_UNIX, PF_X25 for the domain in Python.
The hostname is the address of the device in the network for the regular user.
We can have a string as a host name for example www.xyz.com. A hostname can also be a dotted-quad address or an IPV6 address in colon using a dot for the notation for example 18.104.22.168. The Integer reads as a binary address in host byte order.
A port in a network is an endpoint for the operating system. Every server provides communications using the port number for different users. A port number can be an integer value as well as a string that contains the port number.
Python Socket module
In Python networking, we have to import the socket module that provides function and objects to program for sockets of devices. We have different methods of sockets for a client, server, and some standard methods.
|socket()||This method will create a socket. After creating a socket we can perform different operations. In this method, we have to pass socket_family, socket_type, protocol.|
|recv()||It is general purpose method to receives a message through TCP.|
|send()||It will send a TCP message.|
|recvfrom()||This is a general purpose for receiving a message of UDP.|
|sendto()||We can use this method to send a UDP message.|
|close()||This method will close the connection between sockets.|
|gethostname()||We can use this method to fetch the name of the host. we have to provide an address to the method.|
|bind()||It will bind the socket to the address which we pass to the method as an argument. We have to pass the host name and port number.|
|listen()||The method for a server that will set up as well as initiate the TCP listener for transfer of data over the network.|
|accept()||This method work for the server to wait for receiving the connection, once it receives the connection it will accept the connection.|
|connect()||It is a client socket method. The method starts an active TCP server connection for the client machine.|
Syntax for socket method
To create a socket we have to use the socket() method. We must use the below syntax for our program.
socket (socket_family, socket_type, protocol)
Here, socket family can be AF_UNIX or AF_INET. Type for socket can be SOCK_STREAM for connection-oriented protocols or SOCK_DGRAM for connectionless protocols.
The default value of the protocol is 0.
import socket try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print("Socket successfully created") except socket.error as err: print("socket creation failed with error %s" %(err)) addr = socket.gethostbyname('www.google.com') print('Address of www.google.com:',addr)
Socket successfully created Address of www.google.com: 22.214.171.124
Socket module for simple server
In Python networking programming, we can use the socket module for the servers over the network. The socket modules provide built in functions that we can use in our program. To use the methods we have to create a socket object, then we can setup a socket server.
We have to call the bind() method to specify a port to use the service of the desired host.
import socket #create a socket object s = socket.socket() print ("Socket successfully created") port = 9999 s.bind(('', port)) print("socket binded to %s" %(port)) #socket will start listening s.listen(5) print("socket is listening") while True: # Establish connection with client. c,addr = s.accept() print('Got connection from', addr) # Close the connection with the client c.close() print('Connection is now close')
In above example, we will create a simple server program. We will create the socket object and then socket will start to listen. After that we have to use the accept() method to accept the request of the client.
ocket successfully created socket binded to 9999 socket is listening Got connection from ('127.0.0.1', 59876) Connection is now closed
Socket module for simple Client
In Python networking programming, we can use the socket module for client machine also. In socket module, there is various module program a client machine.
We have to use the socket.connect() method to connect to an opens a TCP connection. We should provide the hostname and the port number. Once we can get an open socket we can perform different operations such as reading the file.Once we are done we have to close the connection.
import socket # create a socket object sock= socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() port = 7999 # connection to hostname on the port. sock.connect((host, port)) msg = sock.recv(1024) sock.close() print (msg)
In above example, we will create a simple client program. Before we run the program, we have to open the server program in the background we created earlier.
After opening that, run the program and you will get the below output.
Thank you for connecting
Here we will conclude the topic of Python Networking programming if any questions feel free to ask in comments below.