Book Image

Python Network Programming

By : Abhishek Ratan, Eric Chou, Pradeeban Kathiravelu, Dr. M. O. Faruque Sarker
Book Image

Python Network Programming

By: Abhishek Ratan, Eric Chou, Pradeeban Kathiravelu, Dr. M. O. Faruque Sarker

Overview of this book

This Learning Path highlights major aspects of Python network programming such as writing simple networking clients, creating and deploying SDN and NFV systems, and extending your network with Mininet. You’ll also learn how to automate legacy and the latest network devices. As you progress through the chapters, you’ll use Python for DevOps and open source tools to test, secure, and analyze your network. Toward the end, you'll develop client-side applications, such as web API clients, email clients, SSH, and FTP, using socket programming. By the end of this Learning Path, you will have learned how to analyze a network's security vulnerabilities using advanced network packet capture and analysis techniques. This Learning Path includes content from the following Packt products: • Practical Network Automation by Abhishek Ratan • Mastering Python Networking by Eric Chou • Python Network Programming Cookbook, Second Edition by Pradeeban Kathiravelu, Dr. M. O. Faruque Sarker
Table of Contents (30 chapters)
Title Page
Copyright
About Packt
Contributors
Preface
Index

Writing a simple TCP echo client/server application


After testing with basic socket APIs in Python, let us create a TCP socket server and client now. Here, you will have the chance to utilize your basic knowledge gained in the previous recipes.

How to do it...

In this example, a server will echo whatever it receives from the client. We will use the Python argparse module to specify the TCP port from a command line. Both the server and client script will take this argument.

First, we create the server. We start by creating a TCP socket object. Then, we set the reuse address so that we can run the server as many times as we need. We bind the socket to the given port on our local machine. In the listening stage, we make sure we listen to multiple clients in a queue using the backlog argument to the listen() method. Finally, we wait for the client to be connected and send some data to the server. When the data is received, the server echoes back the data to the client.

Listing 1.13a shows how to...