0% found this document useful (0 votes)
19 views20 pages

PYTHON Unit 4

The document provides an overview of client-server networking, detailing the differences between TCP and UDP protocols, socket programming, and the implementation of client-server applications in Python. It explains the roles of servers and clients, the importance of IP addresses and port numbers, and includes example code for establishing TCP and UDP connections. Additionally, it highlights the characteristics and limitations of both TCP and UDP communication methods.

Uploaded by

nirmala.mca
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views20 pages

PYTHON Unit 4

The document provides an overview of client-server networking, detailing the differences between TCP and UDP protocols, socket programming, and the implementation of client-server applications in Python. It explains the roles of servers and clients, the importance of IP addresses and port numbers, and includes example code for establishing TCP and UDP connections. Additionally, it highlights the characteristics and limitations of both TCP and UDP communication methods.

Uploaded by

nirmala.mca
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY

16CA5202 – PYTHON PROGRAMMING


(Autonomous)
UNIT – IV – NETWORK PROGRAMMING

Introduction to Client – Server Networking, UDP, TCP, Socket names and DNS ,
HTTP Clients and HTTP Servers
Table of Contents

INTRODUCTION TO CLIENT / SERVER NETWORKING .................................................. 1


TCP ............................................................................................................................................. 4
UDP............................................................................................................................................. 9
SOCKET NAMES AND DNS ................................................................................................. 11
HTTP CLIENTS & HTTP SERVERS ..................................................................................... 12

INTRODUCTION TO CLIENT / SERVER


NETWORKING

Client / Server

The server, a piece of hardware or software, is providing a "service" that is needed


by one or more clients, users of the service.

Its sole purpose of existence is to wait for (client) requests, service those clients,
then wait for more requests.

A user or client computer is retrieving information from a server across the Internet.

Hardware Client/Server Architecture

Print(er) servers are examples of hardware servers. They process incoming print jobs
and send them to a printer (or some other printing device) attached to such a system.
Such a computer is generally network-accessible and client machines would send
print requests.
Another example of a hardware server is a file server. These are typically machines
with large, generalized storage capacity, which is remotely accessible to clients.

Software Client/Server Architecture

Software servers also run on a piece of hardware but do not have dedicated
peripheral devices as hardware servers do, i.e., printers, disk drives, etc.
The primary services provided by software servers include program execution, data
transfer retrieval, aggregation, update, or other types of pr ogrammed or data
manipulation.
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – IV – NETWORK PROGRAMMING

 One of the more common software servers today is the Web server. A corporate
machine is set up with Web pages and/or Web applications, then the Web server
is started. The job of such a server is to accept client requests, se nd back Web
pages to (Web) clients, i.e., browsers on users' computers, and wait for the next
client request. These servers are started with the expectation of "running forever."
 Database servers are another kind of software server. They take client reque sts for
either storage or retrieval, perform that service, then wait for more business.

Encoding & Decoding


Bytes are the actual binary numbers that computers transmit back and forth during
network communication, each consisting of eight binary digits an d ranging from the
binary value 00000000 to 11111111 and thus from the decimal integer 0 to 255.

Encoding is the process of taking character strings and converting them into
bytes for data transmission using communication channel.

Decoding is the process of converting bytes into character format


understandable by the user

Internet Protocol

The Internet Protocol is a scheme for imposing a uniform system of addresses on all
of the Internet-connected computers in the entire world and to make it possible f or
packets to travel from one end of the Internet to the other

IP Addresses

IP Addresses The original version of the Internet Protocol assigns a 4 -byte address to
every computer connected to the worldwide network. Such addresses are usually
written as four decimal numbers, separated by periods, which each represent a single
byte of the address. Each number can therefore range from 0 to 255. So, a traditional
four-byte IP address looks like this: 130.207.244.244

import socket
if __name__ == '__main__':
hostname = '127.0.0.1' #www.python.org
addr = socket.gethostbyname(hostname)
print('The IP address of {} is {}'.format(hostname, addr))

OUTPUT
The IP address of localhost is 127.0.0.1
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – IV – NETWORK PROGRAMMING

For Client-Server communication, sockets are to be configured at the two ends


to initiate a connection, listen for incoming messages and then send the
responses at both ends thereby establishing a bidirectional communication.

Sockets are the end-point of a two-way communication link. An endpoint is a


combination of IP address and the port number.

It is an object used to connect 2 process. The process may be in the same


machine or in the remote machine

DIFFERENCE BETWEEN TCP AND UDP


TCP UDP
Reliable, guaranteed Unreliable. Instead, prompt delivery of
packets.
Connection-oriented Connectionless
Used in applications that require safety Used in media applications. (eg. video or
guarantee. (eg.File applications.) voice transmissions.)
Flow control, sequencing of packets, No flow or sequence control, user must
error-control. handle these manually.
Uses byte stream as unit of transfer. Uses datagrams as unit of transfer.
stream sockets) (datagram sockets)
Allows to send multiple packets with a ------
single ACK
Allows two-way data exchange, once the Allows data to be transferred in one
connection is established. (full-duplex) direction at once. (half-duplex)

Eg. Telnet uses stream sockets e.g. TFTP (trivial file transfer protocol)
uses datagram sockets

Port Numbers

A port number is a way to identify a specific process to which an Internet or other


network message is to be forwarded when it arrives at a server.
Port numbers allow different applications on the same computer to share network
resources simultaneously.

Specifying port numbers ensure two systems communicate correctly. Below are a list
of common port numbers and their associated services.
• 20 - FTP (file transfers)
• 25 - SMTP (mail servers)
• 80 - HTTP (websites)
• 443 - HTTPS (secure websites)
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – IV – NETWORK PROGRAMMING

Port numbers are associated with network addresses. For example , in TCP/IP
networking, both TCP and UDP utilize their own set of ports that work together with
IP addresses
Port numbers work like telephone extensions.

TCP

Socket: A socket is an endpoint for communication between two machines.


The name suggests socket is nothing but a pipe that will deliver the stuff from one
end to another end.
The medium can be the Local Area Newtork, Wide Area Network or the Internet.
Sockets can use both TCP and UDP protocols.

SOCKET CREATION IN PYTHON: SOCKET()

sd = socket.socket (int domain, int type)

The socket() system call creates a socket

Domain is the address family specification

Family / Domain Description


AF_INET Internet protocols like TCP,UDP
AF_UNIX for Unix internal protocols
The type is the socket type

Type Description
SOCK_STREAM For stream sockets - TCP
SOCK_DGRAM For datagram connections - UDP

Server Socket Methods


s.bind() This method binds address(port,hostname) pait to
socket
s.listen() This method sets up and starts TCP listener
s.accept() This passively accepts TCP client connection waiting
until connection arrives
Client Socket Methods
s.connect() This method actively initiates TCP server connection
General Socket Methods
s.recv() This method receives TCP Message
s.send() This method sends a TCP Message
s.sendto() This method Transmits UDP Message
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – IV – NETWORK PROGRAMMING

s.recvfrom() This Method receives UDP message


s.close() This method closes socket
socket.gethostname() Returns the hostname

Simple TCP – CLIENT SERVER PROGRAM


#client
#!/usr/bin/env python

import socket
import base64

TCP_IP = '127.0.0.1'
TCP_PORT = 62
BUFFER_SIZE = 1024
MESSAGE = "Hello, World!"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s.sendall(MESSAGE.encode('utf-8'))
#s.send(MESSAGE)
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – IV – NETWORK PROGRAMMING

data = s.recv(BUFFER_SIZE)
s.close()

print ("received data:", data)

#server program
#!/usr/bin/env python
#server
import socket
import base64
TCP_IP = '127.0.0.1'
TCP_PORT = 62
BUFFER_SIZE = 20 # Normally 1024, but we want fast response

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)

conn, addr = s.accept()


print ('Connection address:', addr)
while 1:
data = conn.recv(BUFFER_SIZE)
if not data: break
print ("received data:", data)
conn.send(data) # echo
conn.close()

RESTART: C:\Users\Nirmalaa\AppData\Local\Programs\Python\Python36-
32\server.py
Connection address: ('127.0.0.1', 4743)
received data: b'Hello, World!'
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – IV – NETWORK PROGRAMMING

Write a program to demonstrate TCP Client server establishment and receiv e a message from client and the server
converts it into Uppercase and sends back to the client.

Server socket
import socket 1. First we import the python socket library.
host = "127.0.0.1" 2. We define two variables, a host and a port, here the local
port = 5000 machine is the host thus ip address of 127.0.0.1 & the port
//DEFAULT PROTOCOL IS TCP number chosen is 5000 and it is advised to use anything
mySocket = above 1024 as upto 1024 core services use the ports
socket.socket(socket.AF_INET,socket.SOCK_STREAM) 3. Then we define a variable mySocket which is an instance
mySocket.bind((host,port)) of a Python socket
mySocket.listen(1) 4. In server it is important to bind the socket to host and port
print("SOCKET RUNNING ") thus we bind it, tip: bind takes a Tuple, thus we have
(conn, addr)= mySocket.accept() double brackets surrounding it
print("Connection = ",conn) 5. Then we call the listen method and pass 1 to it so that it
print("address ",addr) will perpetually listen till we close the connection
print ("Connection : " + str(addr)) 6. Then we have two variables conn and addr which will hold
while True: the connection from client and the address of the client
data = conn.recv(1024).decode() 7. Then we print the clients address and create another
if not data: variable data which is receiving data from connection and
break we have to decode it, this step is necessary for Python 3 as
print ("from connected user: " + str(data)) normal string with str won’t pass through socket and str
does not implement buffer interface anymore.
data = str(data).upper() 8. We run all this in a while true loop so unless the the
print ("sending: " + str(data)) connection is closed we run this and server’s keeps on
conn.send(data.encode()) listening when the data is received server transforms in
into uppercase by calling upper method and sends the
conn.close() string back to client and we encode too as normal string
will fail to transmit properly
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – IV – NETWORK PROGRAMMING

Client Socket
import socket 1. Well similarly we import the socket module and create
host = '127.0.0.1' similar variable mySocket and connect via passing server’s
port = 5000 address 127.0.0.1 and port 5000
mySocket = socket.socket() 2. However, one noticeable difference is we do not have to
mySocket.connect((host,port)) add bind as client does not need to bind, this is a very
print("CLIENT RUNNING ") basic yet important concept of network programming
message = input(" Enter Message -> ") 3. Use the input method to ask for input from the user
while message != 'q': 4. Then while the character typed is not “q” we keep running
mySocket.send(message.encode()) the loop and send the message by encoding it and when we
data = mySocket.recv(1024).decode() received the processed data we decode it and print

print ('Received from server: ' + data)

message = input(" Enter Message -> ")


mySocket.close()
SERVER OUTPUT CLIENT OUTPUT
RESTART: RESTART:
C:/Users/Nirmalaa/AppData/Local/Programs/Python/Python3 C:/Users/Nirmalaa/AppData/Local/Programs/Python/Python3
6-32/tcpserver.py 6-32/tcpclient.py

SERVER STARTED ... CLIENT STARTED ....


Connection from: ('127.0.0.1', 2754) -> hello
from connected user: hello Received from server: HELLO
sending: HELLO -> i am fine
from connected user: i am fine Received from server: I AM FINE
sending: I AM FINE>>> -> q>>
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – IV – NETWORK PROGRAMMING

UDP

The user datagram protocol (UDP) works differently from TCP/IP. Wh ere TCP is
a stream oriented protocol, ensuring that all of the data is transmitted in the right
order, UDP is a message oriented protocol. UDP does not require a long-lived
connection, so setting up a UDP socket is a little simpler. On the other hand, UDP
messages must fit within a single packet (for IPv4, that means they can only hold
65,507 bytes because the 65,535 byte packet also includes header information) and
delivery is not guaranteed as it is with TCP.

we defined TCP socket by merely writing S=socket.socket(), that is without providing


the socket_family and the socket_type. If we do not mention
the socket_family and socket_type, then by default it is TCP. So, if we want to create a UDP
socket than we have to specify socket_family and socket_type explicitly.

Properties of UDP:
 The UDP does not provide guaranteed delivery of message packets. If for
some issue in a network if a packet is lost it could be lost forever.
 Since there is no guaranty of assured delivery of messages UDP is an
unreliable protocol.
 The underlying mechanisms that implement UDP involve no connection -
based communication. There is no streaming of data between a UDP server or
and an UDP Client.
 An UDP client can send "n" number of distinct packets to an UDP server and
it could also receive "n" number of distinct packets as replies from the UDP
server.
 Since UDP is connectionless protocol the overhead involved in UDP is less
compared to a connection based protocol like TCP.
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – IV – NETWORK PROGRAMMING

UDP SERVER SOCKET


import socket RESTART:
C:\Users\Nirmalaa\AppData\Local\Programs\Python\Python
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) 36-32\udpserver.py
# For UDP Waiting for client...
# Host IP Received Messages: b'good' from ('169.254.74.87', 51639)
udp_host = socket.gethostname() Waiting for client...
# specified port to connect Received Messages: b'morning' from ('169.254.74.87',
51639)
udp_port = 12345 Waiting for client...
sock.bind((udp_host,udp_port)) Received Messages: b'bye' from ('169.254.74.87', 51639)

while True:
print ("Waiting for client...")
#receive data from client
data,addr = sock.recvfrom(1024)
print ("Received Messages:",data," from",addr)
if data == b'bye':
break
sock.close()
UDP CLIENT SOCKET
#!usr/bin/python RESTART:
C:/Users/Nirmalaa/AppData/Local/Programs/Python/Python
import socket 36-32/udpclient.py

sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) Enter Message :good


# For UDP UDP target IP: nirmala
UDP target Port: 12345
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – IV – NETWORK PROGRAMMING

udp_host = socket.gethostname() # Host IP


udp_port = 12345 # specified port to connect Enter Message :morning
msg = input("\n Enter Message :") UDP target IP: nirmala
while True: UDP target Port: 12345

print ("UDP target IP:", udp_host) Enter Message :bye


print ("UDP target Port:", udp_port) UDP target IP: nirmala
sock.sendto(msg.encode(),(udp_host,udp_port)) # UDP target Port: 12345
Sending message to UDP server
if msg == 'bye':
break
msg= input("\n Enter Message :")
sock.close()

SOCKET NAMES AND DNS


A socket is one endpoint of a communication channel used by programs to p ass data back and forth locally or across the Internet.

Sockets have two primary properties controlling the way they send data:
 the address family controls the OSI network layer protocol
 the socket type controls the transport layer protocol.
Python supports three address families.
 The most common, AF_INET, is used for IPv4 Internet addressing.
 IPv4 addresses are made up of four octal values separated by dots (e.g., 10.1.1.5 and 127.0.0.1). These values are more
commonly referred to as “IP addresses.” Almost all Internet networking is done using IP version 4 at this time.
 AF_INET6 is used for IPv6 Internet addressing. IPv6 is the “next generation” version of the Internet protocol, and
supports 128-bit addresses, traffic shaping, and routing features not available under IPv4.
 AF_UNIX is the address family for Unix Domain Sockets (UDS), an interprocess communication protocol available on
POSIX-compliant systems.
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – IV – NETWORK PROGRAMMING

Socket includes functions to interface with the domain name services on the network,
to convert the host name of a server into its numerical network address.
Applications do not need to convert addresses explicitly before using them to connect
to a server, but it can be useful when reporting errors to include the numerical
address as well as the name value being used.

To find the official name of the current host, use gethostname().


gethostname()

import socket
try:
host = socket.gethostname()
print (host)
except socket.error as e:
print ("cannot resolve hostname: ", e)

OUTPUT
= RESTART: C:/Users/Nirmalaa/AppData/Local/Programs/Python/Python36 -
32/n2.py =
nirmala

Translate a host name to IPv4 address format


gethostbyname()
import socket
host1 = "www.python.org"
try:
host = socket.gethostbyname(host1)
print (host)
except socket.error as e:
print ("cannot resolve hostname: ", e)

OUTPUT

= RESTART: C:/Users/Nirmalaa/AppData/Local/Programs/Python/Python36 -
32/n2.py =
151.101.8.223

gethostbyname_ex()
For access to more naming information about a serv er, use gethostbyname_ex(). It
returns the canonical hostname of the server, any aliases, and all of the available IP
addresses that can be used to reach it.

import socket
host ='www.python.org'
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – IV – NETWORK PROGRAMMING

print (host)
try :
hostname1, aliases1, addresses1 = socket.gethostbyname_ex(host)
print (' Hostname:', hostname1)
print (' Aliases :', aliases1)
print (' Addresses:', addresses1)
except socket.error as msg:
print ('ERROR: %s' % (msg))

= RESTART: C:/Users/Nirmalaa/AppData/Local/Programs/Python/Python36-
32/n3.py =
www.python.org
Hostname: dualstack.python.map.fastly.net
Aliases : ['www.python.org']
Addresses: ['151.101.8.223']

Translate a IPv4 address format into hostname


gethostbyaddr()

import socket
try:
hostname1, aliases1, addresses1 = socket.gethostbyaddr('127.0.0.1')
print (' Hostname:', hostname1)
print (' Aliases :', aliases1)
print (' Addresses:', addresses1)
except socket.error as msg:
print ('ERROR: %s' % (msg))

= RESTART: C:\Users\Nirmalaa\AppData\Local\Programs\Python\Python36-
32\n3.py =
Hostname: nirmala
Aliases : []
Addresses: ['127.0.0.1']

Service Information

In addition to an IP address, each socket address includes an integer port number.


Many applications can run on the same host, listening on a single IP address, but
only one socket at a time can use a port at that address. The combination of IP
address, protocol, and port number uniquely identify a communication channel and
ensure that messages sent through a socket arrive at the correct destination.
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – IV – NETWORK PROGRAMMING

The IP address provides the connection to the correct machine, it cannot distinguish
the different service that is required. The port is used to distinguish the application.
It is a value from 0 to 65535. The combination of IP address, port and protocol is
called a socket, and has to be unique for every service. The port numbers area
available for both TCP and UDP, and when referred to in conjunction with the IP
address it specifies the "socket".

Sample Services Database


services protocol port number
echo tcp 7
echo udp 7
ftp tcp 21
telnet tcp 23
domain tcp / udp 53
http tcp/udp 80
rtelnet tcp/udp 107
snmp tcp / udp 161
https tcp / udp 443

getservbyname()
Services are often named by name too. The getservbyname() function is used to
retrieve information about services (the protocol being used by the service and the
port number assigned for the service). The information is retrieved from the service
database file /etc/services

import socket
#Service list has a list of application protocols
serviceList =["http","https","SMTP","SNMP"]
underlyingProtocol = "TCP"
print("======>Services and their port numbers<======")
for service in serviceList:
portNum = socket.getservbyname(service, underlyingProtocol)
print("The service {} uses port number {} ".format(service, portNum))

======>Services and their port numbers<======


The service http uses port number 80
The service https uses port number 443
The service SMTP uses port number 25
Traceback (most recent call last):

getservbyport()--Get Service Name for Port Number

import socket
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – IV – NETWORK PROGRAMMING

#Service list has a list of application protocols


serviceList =[80,443,25]
underlyingProtocol = "TCP"
print("======>Services and their port numbers<======")
for service in serviceList:
portNum = socket.getservbyport(service, underlyingProtocol)
print("The service {} uses port number {} ".format(service, portNum))

runfile('C:/Users/Nirmalaa/np1.py', wdir='C:/Users/Nirmalaa')
======>Services and their port numbers<======
The service 80 uses port number http
The service 443 uses port number https
The service 25 uses port number smtp

getaddrinfo()
getaddrinfo() converts the basic address of a service into a list of tup les with all of
the information necessary to make a connection. The contents of each tuple will vary,
containing different network families or protocols.

If we know a network service by host name like example.org or the IP address of the
network service either in form of IPv4 or IPv6 along with the port number of the
network service, getaddrinfo() will return a list of tuples containing information
about socket(s) that can be created with the service.

host: The host parameter takes either an ip address or a host name.


The ip address can be either an ipv4 address or an ipv6 address.
When a host name is used the Domain Name Service(DNS)
will be used for resolving the name into an IP address.

port: The port number of the service. If zero information is returned for
all supported socket types.

import socket,sys
try:
from urllib.parse import urlparse
except ImportError:
from urlparse import urlparse

addrInfo = socket.getaddrinfo("www.python.org",80)
# print socket tuples
print(addrInfo)
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – IV – NETWORK PROGRAMMING

= RESTART: C:/Users/Nirmalaa/AppData/Local/Programs/Python/Python36 -
32/N7.PY =
[(<AddressFamily.AF_INET: 2>, 0, 0, '', ('151.101.8.223', 80))]

HTTP CLIENTS & HTTP SERVERS


https://www.afternerd.com/blog/python-http-server/

Imagine you pull up your Chrome browser and type www.yahoo.com in the address bar.

When www.yahoo.com is typed on the browser, The browser will create a your browser will
create a network message called an HTTP request.

The HTTP client sends a request to the server in the form of a request method, URI, and
protocol version, followed by a MIME-like message containing request modifiers, client
information, and possible body content over a TCP/IP connection.

The HTTP server responds with a status line, including the message's protocol version and a
success or error code, followed by a MIME-like message containing server information, entity
meta information, and possible entity-body content.

HTTP

HTTP stands for HyperText Transfer Protocol. This is a basis for data communication in the
internet. The data communication starts with a request sent from a client and ends with the
response received from a web server.

 A website URL starting with “http://” is entered in a web browser from a computer
(client). The browser can be a Chrome, Firefox, Edge, Safari, Opera or anything else.
 Browser sends a request sent to the web server that hosts the website.
 The web server then returns a response as a HTML page or any other document format
to the browser.
 Browser displays the response from the server to the user.
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – IV – NETWORK PROGRAMMING

HTTP Request Structure from Client


A simple request message from a client computer consists of the following components:
 A request line to get a required resource, for example a request GET
/content/page1.html is requesting a resource called /content/page1.html from the server.
 Headers (Example – Accept-Language: EN).
 An empty line.
 A message body which is optional.
 All the lines should end with a carriage return and line feed. The empty line should
only contains carriage return and line feed without any spaces.

HTTP Response Structure from Web Server


A simple response from the server contains the following components:
 HTTP Status Code (For example HTTP/1.1 301 Moved Permanently, means the
requested resource was permanently moved and redirecting to some other resource).
 Headers (Example – Content-Type: html)
 An empty line.
 A message body which is optional.
 All the lines in the server response should end with a carriage return and line feed.
Similar to request, the empty line in a response also should only have carriage return
and line feed without any spaces.

The Requests library in Python helps to interact with a HTTP based API in python.

Steps to be followed

Installing the requests library


Pip install requests
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – IV – NETWORK PROGRAMMING

Making GET Requests


Eg1.py

import requests

def main():
# we define a request object that is equal to requests.get('API')
req = requests.get('http://google.com')
# we then print out the http status_code that was returned on making this request
# you should see a successfull '200' code being returned.
print(req.status_code)

if __name__ == '__main__':
main()

C:\python>python eg1.py
200

Eg2.py
import requests
# Get the headers of a given URL
resp = requests.head("http://www.google.com")
print ("\n The Status Code : ",resp.status_code)
print("\n")
print ("\n The Text Info :", resp.text)
print("\n")
print("\n The Header info :", resp.headers)
print("\n")

C:\python>python eg2.py
('\n The Status Code : ', 200)

('\n The Text Info :', u'')

('\n The Header info :', {'Content-Length': '5386', 'X-XSS-Protection': '1; mode
=block', 'Content-Encoding': 'gzip', 'Set-Cookie': '1P_JAR=2018-10-04-06; expire
s=Sat, 03-Nov-2018 06:58:08 GMT; path=/; domain=.google.com, NID=140=FLQU-hJeCoE
gb-N8DqB6Qt2R2VrwRzpamuo5IQss7qAmE79XeK3rx50ml-D7C4YU-4imXuDZcFyS1-
auC1dHadhZkTR
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – IV – NETWORK PROGRAMMING

0uaXWp9bc7SjCPwR7gpJJntpDxQGZpRN3rEMp; expires=Fri, 05-Apr-2019 06:58:08


GMT; pa
th=/; domain=.google.com; HttpOnly', 'Expires': '-1', 'Server': 'gws', 'Cache-Co
ntrol': 'private, max-age=0', 'Date': 'Thu, 04 Oct 2018 06:58:08 GMT', 'P3P': 'C
P="This is not a P3P policy! See g.co/p3phelp for more info."', 'Content-Type':
'text/html; charset=ISO-8859-1', 'X-Frame-Options': 'SAMEORIGIN'})

//same example using an another web site


import requests
import json

def main():
req = requests.get('http://pokeapi.co/api/v2/pokemon/1/')
print("HTTP Status Code: " + str(req.status_code))
print(req.headers)
json_response = json.loads(req.content)
print("------------------------------------------------------")
print("Pokemon Name: " + json_response['name'])

if __name__ == '__main__':
main()

C:\python>python sample1.py
HTTP Status Code: 200
{'Expect-CT': 'max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn
-cgi/beacon/expect-ct"', 'Access-Control-Allow-Headers': 'Authorization, Origin,
X-Requested-With, Content-Type, Accept', 'Content-Encoding': 'gzip', 'Transfer-
Encoding': 'chunked', 'Set-Cookie': '__cfduid=dbcc17ab59a72728a53c7b34ffdb2033c1
538636858; expires=Fri, 04-Oct-19 07:07:38 GMT; path=/; domain=.pokeapi.co; Http
Only; Secure', 'Vary': 'Accept-Encoding', 'Server': 'cloudflare', 'Last-Modified
': 'Sat, 22 Sep 2018 23:55:28 GMT', 'Connection': 'keep-alive', 'Date': 'Thu, 04
Oct 2018 07:07:39 GMT', 'Access-Control-Allow-Origin': '*', 'Access-Control-All
ow-Methods': 'GET, OPTIONS', 'Content-Type': 'application/json', 'CF-RAY': '4645
d00f7c673192-SIN'}
------------------------------------------------------
Pokemon Name: bulbasaur

 A medium for communication, specifically a protocol for two systems to interact. Also
called HTTP communication protocol
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – IV – NETWORK PROGRAMMING

 A protocol to ask for the required details from the server. This could be in any form of
formatted data. Most commonly used formats are XML and Json.
 Server responds by sending a Response in any form of formatted data, here also it
could be XML or JSON.

To Summarize: A Client and a Server establishes a connection using HTTP protocol. Once
the connection is established, Client sends across the request to the Server in the form of XML
or JSON which both entities (Client and Server) understand. After understanding the request
Server responds with appropriate data by sending back a Response

You might also like