Introduction to Python – Network Programming

If You are interested to learn about the python – MySQL Database access

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 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.

Python provides two levels of access to network programming. These are – 

  • Low-Level Access: At the low level, you can access the basic socket support of the operating system. You can implement client and server for both connection-oriented and connectionless protocols.
  • High-Level Access: At the high level allows to implement protocols like HTTP, FTP, etc.

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 −

Sr.No.Term & Description
1DomainThe 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.
2typeThe type of communications between the two endpoints, typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols.
3protocolTypically zero, this may be used to identify a variant of a protocol within a domain and type.
4hostnameThe 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) notationA string “<broadcast>”, which specifies an INADDR_BROADCAST address.A zero-length string, which specifies INADDR_ANY, orAn Integer, interpreted as a binary address in host byte order.
5portEach 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

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

Client Socket Methods

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

General Socket Methods

Sr.No.Method & Description
1s.recv()This method receives TCP message
2s.send()This method transmits TCP message
3s.recvfrom()This method receives UDP message
4s.sendto()This method transmits UDP message
5s.close()This method closes socket
6socket.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 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.

ProtocolCommon functionPort NoPython module
HTTPWeb pages80httplib, urllib, xmlrpclib
NNTPUsenet news119nntplib
FTPFile transfers20ftplib, urllib
SMTPSending email25smtplib
POP3Fetching email110poplib
IMAP4Fetching email143imaplib
TelnetCommand lines23telnetlib
GopherDocument transfers70gopherlib, 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 −

  • Unix Socket Programming.
  • Python Socket Library and Modules.

Socket Client Methods

This method is used on the client side. Let’s see this method in detail – 

Function NameDescription
s.connect()Actively starts the TCP server connection

Socket General Methods

These are the general methods of the socket module. Let’s see each method in detail.

Function NameDescription
s.send()Sends the TCP message
s.sendto()Sends the UDP message
s.recv()Receives the TCP message
s.recvfrom()Receives the UDP message
s.close()Close the socket
socket.ghostname()Returns the host name

Simple Server Client Program

Server

A server has a bind() method which binds it to a specific IP and port so that it can listen to incoming requests on that IP and port. A server has a listen() method which puts the server into listening mode. This allows the server to listen to incoming connections. And last a server has an accept() and close() method. The accept method initiates a connection with the client and the close method closes the connection with the client. 

Example: Network Programming Server-Side

  • Python3
# first of all import the socket libraryimport socket # next create a socket objects = socket.socket()print ("Socket successfully created") # reserve a port on your computer in our# case it is 40674 but it can be anythingport = 40674 # Next bind to the port# we have not typed any ip in the ip field# instead we have inputted an empty string# this makes the server listen to requests# coming from other computers on the networks.bind(('', port))print ("socket binded to %s" %(port)) # put the socket into listening modes.listen(5)    print ("socket is listening") # a forever loop until we interrupt it or# an error occurswhile True: # Establish connection with client.c, addr = s.accept()print ('Got connection from', addr ) # send a thank you message to the client.c.send(b'Thank you for connecting') # Close the connection with the clientc.close()

Explanation:

  • We made a socket object and reserved a port on our pc.
  • After that, we bound our server to the specified port. Passing an empty string means that the server can listen to incoming connections from other computers as well. If we would have passed 127.0.0.1 then it would have listened to only those calls made within the local computer.
  • After that, we put the server into listening mode. 5 here means that 5 connections are kept waiting if the server is busy and if a 6th socket tries to connect then the connection is refused.
  • At last, we make a while loop and start to accept all incoming connections and close those connections after a thank you message to all connected sockets.

Client

Now we need something with which a server can interact. We could tenet to the server like this just to know that our server is working. Type these commands in the terminal:

# start the server
python server.py

# keep the above terminal open
# now open another terminal and type:

telnet localhost 12345

Output :

network programing server side

In the telnet terminal you will get this:

network programming telnet server

This output shows that our server is working. Now for the client-side: 

Example: Network Programming Client Side

  • Python3
# Import socket moduleimport socket # Create a socket objects = socket.socket() # Define the port on which you want to connectport = 40674 # connect to the server on local computers.connect(('127.0.0.1', port)) # receive data from the serverprint(s.recv(1024)) # close the connections.close()

Output:

python network programming server client
python network programming client side

Explanation:

  • We connect to localhost on port 40674 (the port on which our server runs) and lastly, we receive data from the server and close the connection.
  • Now save this file as client.py and run it from the terminal after starting the server script.
Introduction to Python – Network Programming
Show Buttons
Hide Buttons