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:
|Domain||The family of protocols for transportation mechanisms.|
|type||type of communication between two socket endpoints.|
|protocol||The user uses it to identify a variant of a protocol within a domain and type.|
|hostname||A 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)) s.listen(6) while True: c, addr = s.accept() print 'Got connection from', addr c.send('Thank you for the connection') c.close()