Book Image

Python Network Programming Cookbook - Second Edition

By : Pradeeban Kathiravelu, Gary Berger, Dr. M. O. Faruque Sarker
Book Image

Python Network Programming Cookbook - Second Edition

By: Pradeeban Kathiravelu, Gary Berger, Dr. M. O. Faruque Sarker

Overview of this book

Python Network Programming Cookbook - Second Edition highlights the major aspects of network programming in Python, starting from writing simple networking clients to developing and deploying complex Software-Defined Networking (SDN) and Network Functions Virtualization (NFV) systems. It creates the building blocks for many practical web and networking applications that rely on various networking protocols. It presents the power and beauty of Python to solve numerous real-world tasks in the area of network programming, network and system administration, network monitoring, and web-application development. In this edition, you will also be introduced to network modelling to build your own cloud network. You will learn about the concepts and fundamentals of SDN and then extend your network with Mininet. Next, you’ll find recipes on Authentication, Authorization, and Accounting (AAA) and open and proprietary SDN approaches and frameworks. You will also learn to configure the Linux Foundation networking ecosystem and deploy and automate your networks with Python in the cloud and the Internet scale. By the end of this book, you will be able to analyze your network security vulnerabilities using advanced network packet capture and analysis techniques.
Table of Contents (15 chapters)

Writing a simple UDP echo client/server application

As we have developed a simple TCP server and client in the previous recipe, we will now look at how to develop the same with UDP.

How to do it...

This recipe is similar to the previous one, except this one is with UDP. The method recvfrom() reads the messages from the socket and returns the data and the client address.

Listing 1.14a shows how to write a simple UDP echo client/server application as follows:

#!/usr/bin/env python 
# Python Network Programming Cookbook,
Second Edition -- Chapter - 1 # This program is optimized for Python 2.7.12
and Python 3.5.2. # It may run on any other version with/without
modifications. import socket import sys import argparse host = 'localhost' data_payload = 2048 def echo_server(port): """ A simple echo server """ # Create a UDP socket sock = socket.socket(socket.AF_INET,
socket.SOCK_DGRAM) # Bind the socket to the port server_address = (host, port) print ("Starting up echo server
on %s port %s" % server_address) sock.bind(server_address) while True: print ("Waiting to receive message
from client") data, address = sock.
recvfrom(data_payload) print ("received %s bytes
from %s" % (len(data), address)) print ("Data: %s" %data) if data: sent = sock.sendto(data, address) print ("sent %s bytes back
to %s" % (sent, address)) if __name__ == '__main__': parser = argparse.ArgumentParser
(description='Socket Server Example') parser.add_argument('--port', action="store", dest="port", type=int, required=True) given_args = parser.parse_args() port = given_args.port echo_server(port)

On the client side code, we create a client socket using the port argument and connect to the server, as we did in the previous recipe. Then, the client sends the message, Test message. This will be echoed, and the client immediately receives the message back in a few segments.

Listing 1-14b shows the echo client as follows:

#!/usr/bin/env python 
# Python Network Programming Cookbook, Second Edition -- Chapter - 1 
# This program is optimized for Python 2.7.12 and Python 3.5.2. 
# It may run on any other version with/without modifications. 
 
import socket 
import sys 
import argparse 
 
host = 'localhost' 
data_payload = 2048 
 
def echo_client(port): 
    """ A simple echo client """ 
    # Create a UDP socket 
    sock = socket.socket(socket.AF_INET, 
socket.SOCK_DGRAM) server_address = (host, port) print ("Connecting to %s port %s" % server_address) message = 'This is the message. It will be
repeated.' try: # Send data message = "Test message. This will be
echoed" print ("Sending %s" % message) sent = sock.sendto(message.encode
('utf-8'), server_address) # Receive response data, server = sock.recvfrom(data_payload) print ("received %s" % data) finally: print ("Closing connection to the server") sock.close() if __name__ == '__main__': parser = argparse.ArgumentParser
(description='Socket Server Example') parser.add_argument('--port', action="store", dest="port", type=int, required=True) given_args = parser.parse_args() port = given_args.port echo_client(port)
Downloading the example code
Detailed steps to download the code bundle are mentioned in the Preface of this book. The code bundle for the book is also hosted on GitHub at: https://github.com/PacktPublishing/Python-Network-Programming-Cookbook-Second-Edition. We also have other code bundles from our rich catalog of books and videos available at: https://github.com/PacktPublishing/. Check them out!

How it works...

In order to see the client/server interactions, launch the following server script in one console:

$ python 1_14a_echo_server_udp.py --port=9900 
Starting up echo server on localhost port 9900
Waiting to receive message from client
  

Now, run the client from another terminal as follows:

$ python 1_14b_echo_client_udp.py --port=9900 
Connecting to localhost port 9900
Sending Test message. This will be echoed
received Test message. This will be echoed
Closing connection to the server
    
  

Upon receiving the message from the client, the server will also print something similar to the following message:

received 33 bytes from ('127.0.0.1', 43542)
Data: Test message. This will be echoed
sent 33 bytes back to ('127.0.0.1', 43542)
Waiting to receive message from client