Socket Module In Python

Python socket module:

The socket module from the Python Standard Library provides the equivalent of BSD socket interface.

The socket module provides various objects, constants, functions and related exceptions for building full-fledged network applications including client and server programs. 

While such constructs including the functions, classes and methods are listed here let us start with writing a sample client program using python’s socket module and move on to a client-server example using python.

Example client program using python socket module:

#import the socket module

import socket


#Create a socket instance

socketObject = socket.socket()


#Using the socket connect to a this case localhost

socketObject.connect(("localhost", 80))

print("Connected to localhost")


# Send a message to the web server to supply a page as given by Host param of GET request

HTTPMessage = "GET / HTTP/1.1\r\nHost: localhost\r\n Connection: close\r\n\r\n"

bytes       = str.encode(HTTPMessage)




# Receive the data


    data = socketObject.recv(1024)




        print("Connection closed")





Connected to localhost

b'HTTP/1.1 200 OK\r\nDate: Thu, 26 Jan 2019 17:40:19 GMT\r\nServer: Apache/2.4.9 (Unix) PHP/5.5.14 OpenSSL/0.9.8za\r\nLast-Modified: Thu, 26 Jan 2019 17:40:12 GMT\r\nETag: "a5-54702d7591700"\r\nAccept-Ranges: bytes\r\nContent-Length: 165\r\nContent-Type: text/html\r\n\r\n<html>\n\n<head>\n\t<Title>Welcome!</Title>\n\t<link rel="stylesheet" href="MyIST.css">\n\n</head>\n\n<body>\n\t<center><h1>Thanks for visiting!</h1></center>\n</body>\n\n</html>\n\n'


Connection closed

The above program connects to the web server running in localhost at port number 80. It asks for the home page using HTTP GET message by specifying the Host Name of the website.

The program creates a socket instance making a call to the socket() function with default parameter values.

The socket() function takes four parameters all of them initialized with the default values,

socket(family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None)

Since all the four parameters are initialized with the above default values, a call to the socket.socket() will create a socket initialized with  AF_INET protocol family, and the type of the socket created is a streaming socket as specified in SOCK_STREAM.

The connect(call establishes a connection with a remote socket as designated by the address/hostname, port pair which is passed as the parameter to the connect() method.

Using the sendall() method,  the sample program sends a HTTP GET message to the remote socket, in this case a web server running in the same machine.

Through recv() the response from the server is received into a buffer and printed to the console.

Copyright 2024 ©