- Saved searches
- Use saved searches to filter your results more quickly
- License
- PacktPublishing/Python-Network-Programming
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Python — Network Programming
- What is Sockets?
- The socket Module
- Server Socket Methods
- Client Socket Methods
- General Socket Methods
- A Simple Server
- A Simple Client
- Python Internet modules
- Further Readings
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Conquer all your networking challenges with the powerful Python language
License
PacktPublishing/Python-Network-Programming
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Python Network Programming
This Learning Path reviews the core elements of Python and the TCP/IP protocol suite. It 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. This Learning Path will guide you in configuring the Linux Foundation networking ecosystem and deploying automated networks in the cloud. You will gain experience in retrieving network information with flow-based monitoring, a polling mechanism, and data visualization. Toward the end, you’ll develop client-side applications, such as web API clients, email clients, SSH, and FTP, using socket programming and multithreaded or event-driven architectures. 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 Dr. M. O. Faruque Sarker, Pradeeban Kathiravelu
- Create socket-based networks with asynchronous models
- Develop client apps for web APIs, including S3 Amazon and Twitter
- Talk to email and remote network servers with different protocols
- Integrate Python with Cisco, Juniper, and Arista eAPI for automation
- Use Telnet and SSH connections for remote system monitoring
- Interact with websites via XML-RPC, SOAP, and REST APIs
- Build networks with Ryu, OpenDaylight, Floodlight, ONOS, and POX
- Configure virtual networks in different deployment environments
For an optimal student experience, we recommend the following hardware configuration:
- Processor: 2.6 GHz or higher, preferably multi-core
- Memory: 4GB RAM
- Hard disk: 10GB or more
- An Internet connection
You’ll also need the following software installed in advance:
- Operating System: Windows or Linux
- Python (3.5 onward)
- An Ansible installation
- GNS3 (for testing) or real routers
About
Conquer all your networking challenges with the powerful Python language
Python — Network Programming
Python provides two levels of access to network services. At a low level, you can access the basic socket support in the underlying operating system, which allows you to implement clients and servers for both connection-oriented and connectionless protocols.
Python also has libraries that provide higher-level access to specific application-level network protocols, such as FTP, HTTP, and so on.
This chapter gives you understanding on most famous concept in Networking — Socket Programming.
What is Sockets?
Sockets are the endpoints of a bidirectional communications channel. Sockets may communicate within a process, between processes on the same machine, or between processes on different continents.
Sockets may be implemented over a number of different channel types: Unix domain sockets, TCP, UDP, and so on. The socket library provides specific classes for handling the common transports as well as a generic interface for handling the rest.
Sockets have their own vocabulary −
The family of protocols that is used as the transport mechanism. These values are constants such as AF_INET, PF_INET, PF_UNIX, PF_X25, and so on.
The type of communications between the two endpoints, typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols.
Typically zero, this may be used to identify a variant of a protocol within a domain and type.
The identifier of a network interface −
- A string, which can be a host name, a dotted-quad address, or an IPV6 address in colon (and possibly dot) notation
- A string «», which specifies an INADDR_BROADCAST address.
- A zero-length string, which specifies INADDR_ANY, or
- An Integer, interpreted as a binary address in host byte order.
Each server listens for clients calling on one or more ports. A port may be a Fixnum port number, a string containing a port number, or the name of a service.
The socket Module
To create a socket, you must use the socket.socket() function available in socket module, which has the general syntax −
s = socket.socket (socket_family, socket_type, protocol=0)
Here is the description of the parameters −
- socket_family − This is either AF_UNIX or AF_INET, as explained earlier.
- socket_type − This is either SOCK_STREAM or SOCK_DGRAM.
- protocol − This is usually left out, defaulting to 0.
Once you have socket object, then you can use required functions to create your client or server program. Following is the list of functions required −
Server Socket Methods
This method binds address (hostname, port number pair) to socket.
This method sets up and start TCP listener.
This passively accept TCP client connection, waiting until connection arrives (blocking).
Client Socket Methods
This method actively initiates TCP server connection.
General Socket Methods
This method receives TCP message
This method transmits TCP message
This method receives UDP message
This method transmits UDP message
This method closes socket
A Simple Server
To write Internet servers, we use the socket function available in socket module to create a socket object. A socket object is then used to call other functions to setup a socket server.
Now call bind(hostname, port) function to specify a port for your service on the given host.
Next, call the accept method of the returned object. This method waits until a client connects to the port you specified, and then returns a connection object that represents the connection to that client.
#!/usr/bin/python # This is server.py file import socket # Import socket module s = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name port = 12345 # Reserve a port for your service. s.bind((host, port)) # Bind to the port s.listen(5) # Now wait for client connection. while True: c, addr = s.accept() # Establish connection with client. print 'Got connection from', addr c.send('Thank you for connecting') c.close() # Close the connection
A Simple Client
Let us write a very simple client program which opens a connection to a given port 12345 and given host. This is very simple to create a socket client using Python’s socket module function.
The socket.connect(hosname, port ) opens a TCP connection to hostname on the port. Once you have a socket open, you can read from it like any IO object. When done, remember to close it, as you would close a file.
The following code is a very simple client that connects to a given host and port, reads any available data from the socket, and then exits −
#!/usr/bin/python # This is client.py file import socket # Import socket module s = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name port = 12345 # Reserve a port for your service. s.connect((host, port)) print s.recv(1024) s.close() # Close the socket when done
Now run this server.py in background and then run above client.py to see the result.
# Following would start a server in background. $ python server.py & # Once server is started run client as follows: $ python client.py
This would produce following result −
Got connection from ('127.0.0.1', 48437) Thank you for connecting
Python Internet modules
A list of some important modules in Python Network/Internet programming.
Protocol | Common function | Port No | Python module |
---|---|---|---|
HTTP | Web pages | 80 | httplib, urllib, xmlrpclib |
NNTP | Usenet news | 119 | nntplib |
FTP | File transfers | 20 | ftplib, urllib |
SMTP | Sending email | 25 | smtplib |
POP3 | Fetching email | 110 | poplib |
IMAP4 | Fetching email | 143 | imaplib |
Telnet | Command lines | 23 | telnetlib |
Gopher | Document transfers | 70 | gopherlib, urllib |
Please check all the libraries mentioned above to work with FTP, SMTP, POP, and IMAP protocols.
Further Readings
This was a quick start with Socket Programming. It is a vast subject. It is recommended to go through the following link to find more detail −