We now have a youtube channel. Subscribe!

Network Programming in Python



Hello dear readers! welcome back to another section of our tutorial on Python. In this tutorial guide, we will be discussing about the 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 implement clients and servers for both connection-oriented and connectionless protocols.

Python also has libraries that provides very high-level access to a certain application-level network protocols, such as FTP, HTTP, and so on.

This tutorial guide gives you a basic understanding on the most popular concept in Networking - which is the Socket Programing.


What is Sockets?

Sockets are the endpoints of a bi-directional communication route. Sockets may communicate within a process, within processes on same machine, or between the processes on different machines.

Sockets may be implemented over a number of different channel types: TCP, UDP, Unix domain sockets, and so on. The socket library provides specific classes to handle common transports as well as a generic interface for handling the rest.


Socket Vocabularies

Sockets have vocabularies of their own, below is a list of socket vocabularies available -

Sr.No.Term & Description
1
Domain
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.
2
type
The type of communications between the two endpoints, typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols.
3
protocol
Typically zero, this may be used to identify a variant of a protocol within a domain and type.
4
hostname
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 "<broadcast>", 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.
5
port
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 that is available in the socket module.

Syntax

Following below is the syntax for the socket.socket() function -

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

Parameter Details

Following below is the description of the parameters -

  • socket_family - This can be either AF_UNIX or AF_INET, as explained earlier.
  • socket_type - This can be either SOCK_STREAM or the SOCK_DGRM.
  • protocol - This is usually left out, defaulting to 0.

Once you have the socket object, you can then use the required function to create your client or server program. Following is the list of functions that are required -



Server Socket Methods

Sr.No.Method & Description
1
s.bind()
This method binds address (hostname, port number pair) to socket.
2
s.listen()
This method sets up and start TCP listener.
3
s.accept()
This passively accept TCP client connection, waiting until connection arrives (blocking).

Client Socket Methods

Sr.No.Method & Description
1
s.connect()
This method actively initiates TCP server connection.

General Socket Methods

Sr.No.Method & Description
1
s.recv()
This method receives TCP message
2
s.send()
This method transmits TCP message
3
s.recvfrom()
This method receives UDP message
4
s.sendto()
This method transmits UDP message
5
s.close()
This method closes socket
6
socket.gethostname()
Returns the hostname.



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 for calling other functions in order to set up a socket server.

Now call the bind(hostname, port) function in order to specify a port for your server on a given host.

Next, call the accept method of the returned object. This method waits until a client connects to the port that 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
Lets write a simple client program which opens a connection to a given port 12345 and given a host. Its very easy to create a socket client using the Python's socket module function.

The socket.connect(hostname, port) opens up a TCP connection to the hostname on the port. Once you have a socket open, you can read from it like any IO object. When you're done, remember to close it, as you would close a file.

Example
The following code below is a simple client that connects to a given host and port, it reads any available data from socket, and then exists -

#!/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 code 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

Output
When the above code is executed, it will produce the following result -

Got connection from ('127.0.0.1', 48437)
Thank you for connecting



Internet Modules in Python
The following below is a list of important modules in the Python's Network/Internet Programing -

ProtocolCommon functionPort NoPython module
HTTPWeb pages80httplib, urllib, xmlrpclib
NNTPUsenet news119nntplib
FTPFile transfers20ftplib, urllib
SMTPSending email25smtplib
POP3Fetching email110poplib
IMAP4Fetching email143imaplib
TelnetCommand lines23telnetlib
GopherDocument transfers70gopherlib, urllib

Make sure to check the libraries mentioned above to work with FTP, SMTP, IMAP and POP protocols.


Alright guys! This is where we are rounding up for this tutorial post. In our next tutorial, we are going to be studying about how to send Emails using SMTP in Python.

Feel free to ask your questions where necessary and i will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.
© 2023 ‧ WebDesignTutorialz. All rights reserved. Developed by Jago Desain