Python Unit-4 - Part-2
Python Unit-4 - Part-2
Protocol :
A network protocol is an established set of rules that determine how data is transmitted between
different devices in the same network.
It allows connected devices to communicate with each other, regardless of any differences in their
internal processes, structure or design.
Network protocols are the reason you can easily communicate with people all over the world, and
thus play a critical role in modern digital communications.
Important Internet Services & Protocols
o Ping (Packet Inter‐Network Grouper)
o FTP (File Transfer Protocol)
o HTTP (Hypertext Transfer Protocol)
o NNTP (Network News Transfer Protocol)
o SMTP (Simple Mail Transfer Protocol)
o POP3 (Post Office Protocol 3)
o SNMP (Simple Network Management Protocol)
o Telnet (Network Virtual Terminal Protocol)
Sockets :
A server can server many clients at the same time and needs some way of distinguishing between
clients.
A socket is an abstract concept (not a hardware element) used to indicate one end‐point of a link
between two processes.
A client creates a socket and send a request to the server.
On receiving the request, the server creates a new socket which is dedicated to the communication
with that client.
Socket Programming :
Socket programming is a way of connecting two nodes on a network to communicate with each
other. One socket (node) listens on a particular port at an IP, while the other socket reaches out to
the other to form a connection. The server forms the listener socket while the client reaches out to
the server.
They are the real backbones behind web browsing. In simpler terms, there is a server and a client.
Socket programming is started by importing the socket library and making a simple socket.
To do socket programming, first install socket module by using :
pip install sockets
Page : 1
PROGRAMMING IN PYTHON
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Here we made a socket instance and passed it two parameters. The first parameter is AF_INET and
the second one is SOCK_STREAM. AF_INET refers to the address‐family ipv4. The SOCK_STREAM
means connection‐oriented TCP protocol.
KNOWING IP ADDRESS :
An IP(Internet Protocol) address is an identifier assigned to each computer and other device(e.g.,
router, mobile, etc) connected to a TCP/IP network that is used to locate and identify the node in
communication with other nodes on the network. IP addresses are usually written and displayed in
human‐readable notation such as 192.168.1.35 in IPv4(32‐bit IP address).
How to get IP address of your computer in python :
1) Import the socket module.
2) Get the hostname using the socket.gethostname() method and store it in a variable.
3) Find the IP address by passing the hostname as an argument to the socket.gethostbyname()
method and store it in a variable.
4) Print the IP address.
Example :
# importing socket module
import socket
# getting the hostname by socket.gethostname() method
hostname = socket.gethostname()
# getting the IP address using socket.gethostbyname() method
ip_address = socket.gethostbyname(hostname)
# printing the hostname and ip_address
print("Hostname: "+hostname)
print(f"IP Address: " +ip_address)
Output :
Hostname: MYPC
IP Address: 192.168.2.29
Urllib is a package that collects several modules for working with URLs, such as:
urllib.request for opening and reading.
urllib.parse for parsing URLs
urllib.error for the exceptions raised
urllib.robotparser for parsing robot.txt files
If urllib and requests is not present in your environment, execute the below code to install it.
pip install urllib
pip install requests
Page : 2
PROGRAMMING IN PYTHON
urllib.request :
This module helps to define functions and classes to open URLs (mostly HTTP). One of the most
simple ways to open such URLs is :
urllib.request.urlopen(url)
Example :
import urllib.request
request_url = urllib.request.urlopen('https://www.google.co.in/')
print(request_url.read())
urllib.parse :
This module helps to define functions to manipulate URLs and their components parts, to build or
break them. It usually focuses on splitting a URL into small components; or joining different URL
components into URL strings.
o urllib.parse.urlsplit :
urlsplit can be used to take in an url, then split it into parts which can be used for further data
manipulation. For example if we want to programmatically judge if a URL is SSL certified or not then
we apply urlsplit and get the scheme value to decide. In the below example we check the different
parts of the supplied URL.
Example :
import urllib.parse
url='https://www.google.co.in/python'
value = urllib.parse.urlsplit(url)
print(value)
Output :
SplitResult(scheme='https', netloc='www.google.co.in', path='/python', query='', fragment='')
urllib.error :
This module defines the classes for exception raised by urllib.request. Whenever there is an error in
fetching a URL, this module helps in raising exceptions. The following are the exceptions raised :
o URLError – It is raised for the errors in URLs, or errors while fetching the URL due to
connectivity, and has a ‘reason’ property that tells a user the reason of error.
o HTTPError – It is raised for the exotic HTTP errors, such as the authentication request errors. It is
a subclass or URLError. Typical errors include ‘404’ (page not found), ‘403’ (request forbidden),
and ‘401’ (authentication required).
Page : 3
PROGRAMMING IN PYTHON
Example :
# HTTP Error
import urllib.request
import urllib.parse
Output :
<urlopen error [Errno 11001] getaddrinfo failed>
Example :
import requests
import urllib
url="http://www.google.co.in"
webpage=urllib.request.urlopen(url)
print(webpage.read())
Example :
import urllib.request
from urllib.error import URLError
Page : 4
PROGRAMMING IN PYTHON
Downloading an Image from Internet :
Call requests.get(url) with url as the address of the file to download and save the response to a
variable. Use open(filename, mode) with mode as "wb" to open a stream of filename in write‐and‐
binary mode. Call file.write(binary) with binary as the content of the response to write it to file. Use
file.close() to close the stream.
Example :
import requests
url = 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png'
r = requests.get(url, allow_redirects=True)
open('googlelogo.png', 'wb').write(r.content)
SERVER:
A server has a bind(hostname,port) method which binds it to a specific IP and port so that it can
listen to incoming requests on that IP and port. A server has a listen() method which puts the server
into listening mode. This allows the server to listen to incoming connections. And last a server has
an accept() and close() method. The accept method initiates a connection with the client and the
close method closes the connection with the client.
Example :
import socketserver
class Handler_TCPServer(socketserver.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(1024).strip() # self.request ‐ TCP socket connected to the client
print("{} sent:".format(self.client_address[0]))
print(self.data)
self.request.sendall("Acknowledgement from TCP Server".encode())
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# Init the TCP server object, bind it to the localhost on 9999 port
tcp_server = socketserver.TCPServer((HOST, PORT), Handler_TCPServer)
CLIENT :
This is very simple to create a socket client using Python's socket module function.
The socket.connect(hostname, port ) opens a TCP connection to hostname on the port. Once you
have a socket open, you can read from it like any IO object. When done, remember to close it, as
you would close a file.
The following code that connects to a given host and port, reads any available data from the socket:
Page : 5
PROGRAMMING IN PYTHON
Example :
import socket
try:
# Establish connection to TCP server and exchange data
tcp_client.connect((host_ip, server_port))
tcp_client.sendall(data.encode())
# Read data from the TCP server and close the connection
received = tcp_client.recv(1024)
finally:
tcp_client.close()
UDP is a connection‐less protocol. It means a UDP server just catches incoming packets from any
and many hosts without establishing a reliable pipe kind of connection.
SERVER :
Example :
import socket
localIP = "127.0.0.1"
localPort = 20001
bufferSize = 1024
msgFromServer = "Hello UDP Client"
bytesToSend = str.encode(msgFromServer)
Page : 6
PROGRAMMING IN PYTHON
bytesAddressPair = UDPServerSocket.recvfrom(bufferSize)
message = bytesAddressPair[0]
address = bytesAddressPair[1]
clientMsg = "Message from Client:{}".format(message)
clientIP = "Client IP Address:{}".format(address)
print(clientMsg)
print(clientIP)
CLIENT :
Example :
import socket
msgFromClient = "Hello UDP Server"
bytesToSend = str.encode(msgFromClient)
serverAddressPort = ("127.0.0.1", 20001)
bufferSize = 1024
SERVER :
Example :
import socket # Import socket module
port = 60000 # Reserve a port for your service.
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
print('Server listening....')
while True:
conn, addr = s.accept() # Establish connection with client.
Page : 7
PROGRAMMING IN PYTHON
print('Got connection from', addr)
data = conn.recv(1024)
print('Server received', repr(data))
filename='mytext.txt'
f = open(filename,'rb')
l = f.read(1024)
while (l):
conn.send(l)
print('Sent ',repr(l))
l = f.read(1024)
f.close()
print('Done sending')
msg='Thank you for connecting'
byt=msg.encode()
conn.send(byt)
conn.close()
CLIENT :
Example :
import socket # Import socket module
s.connect((host, port))
msg='Hello Server'
byt=msg.encode()
s.send(byt)
f.close()
print('Successfully get the file')
s.close()
print('connection closed')
Page : 8