python network programming

Python Network Programming

Python Network Programming provides two levels of access to network services. One is at the higher level and another is at the lower level. At a lower level, the user is able to access the basic socket support in the underlying operating system. This further allows the user to implement clients and servers for both connection-oriented and connectionless protocols. At the higher level, python has libraries. The user can therefore use it to access specific application-level network protocols, such as FTP, HTTP, and so on.

Python Network Programming sockets

Sockets are known as the endpoints of a bidirectional communications channel. Likewise, these sockets (endpoints) can communicate within a process, between processes on the same machine, or between the processes on the different machines. The user can implement the sockets using different channel types such as Unix domain sockets, TCP, UDP, etc. There is also a socket library that provides specific classes for handling the common transports as well as a generic interface for handling the rest. Here’s a list of the different sockets with their own vocabulary:

DomainThe family of protocols for transportation mechanisms.
typetype of communication between two socket endpoints.
protocolThe user uses it to identify a variant of a protocol within a domain and type.
hostnameA string “<broadcast>”, which specifies an INADDR_BROADCAST address
port A port is a Fixnum port number or a string containing a port number, or the name of a service

Python Socket Module

The user can create a socket module for python network programming using the following syntax:

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

The description of the above parameters is given below :

  • socket_family : This is either AF_UNIX or AF_INET
  • socket_type : This is either AF_UNIX or AF_INET
  • protocol : This is usually left out, defaulting to 0

Initiating a basic python server

The user uses theΒ socketΒ function available in the socket module to create a socket object. A socket object is then used to call other functions to set up a socket server. Now callΒ the bind(hostname, port)Β function to specify aΒ portΒ for your service on the given host.

The next step is to call theΒ acceptΒ method of the returned object. This method waits until a client connects to the port you specified, and then similarly returns aΒ connectionΒ object that represents the connection to that client.

Below is a code for better understanding:

import socket   

s = socket.socket() 
host = socket.gethostname() 
port = 123456789                
s.bind((host, port))        

while True:
   c, addr = s.accept()     
   print 'Got connection from', addr
   c.send('Thank you for the connection')

Discover Our Exciting Courses and Quiz

Enroll now to enhance your skills and knowledge!

Python Online Quiz

Level up your coding skills with our interactive programming quiz!