PYTHON Unit 4
PYTHON Unit 4
Introduction to Client – Server Networking, UDP, TCP, Socket names and DNS ,
HTTP Clients and HTTP Servers
Table of Contents
Client / Server
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.
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 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 is the process of taking character strings and converting them into
bytes for data transmission using communication channel.
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
Eg. Telnet uses stream sockets e.g. TFTP (trivial file transfer protocol)
uses datagram sockets
Port Numbers
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
Type Description
SOCK_STREAM For stream sockets - TCP
SOCK_DGRAM For datagram connections - UDP
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()
#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)
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
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.
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
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
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.
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
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']
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
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".
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))
import socket
HINDUSTHAN COLLEGE OF ENGINEERING & TECHNOLOGY
16CA5202 – PYTHON PROGRAMMING
(Autonomous)
UNIT – IV – NETWORK PROGRAMMING
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.
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))]
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
The Requests library in Python helps to interact with a HTTP based API in python.
Steps to be followed
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 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
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