0% found this document useful (0 votes)
18 views

Python Unit-4 - Part-2

Uploaded by

jkdon2728
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Python Unit-4 - Part-2

Uploaded by

jkdon2728
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

PROGRAMMING IN PYTHON

UNIT – 4 Network Programming


 Network :
 A network is a collection of computers and other devices that can send/receive data between each
other.
 Each machine on a network is called a node.
 Nodes that are fully functional computers are also called hosts.
 Every network node has an address which is a series of bytes that uniquely identify it.
 Addresses are assigned differently on different kinds of networks.

 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

 Python Urllib Module :


Urllib package is the URL handling module for python. It is used to fetch URLs (Uniform Resource
Locators). It uses the urlopen function and is able to fetch URLs using a variety of different
protocols.

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.

Different other functions of urllib.parse are :


Function Use
urllib.parse.urlparse Separates different components of URL
urllib.parse.urlunparse Join different components of URL
urllib.parse.urlsplit It is similar to urlparse() but doesn’t split the params
urllib.parse.urlunsplit Combines the tuple element returned by urlsplit() to form URL

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

# trying to read the URL


try:
x = urllib.request.urlopen('https://www.google.com / search?q = test')
print(x.read())

# Catching the exception generated


except Exception as e :
print(str(e))

Output :
<urlopen error [Errno 11001] getaddrinfo failed>

 Reading the Source Code of a Web Page :


With Python and the requests module, it is easy to read data from the web. Requests is one of the
most widely used library. It allows us to open any HTTP/HTTPS website. A webpage is just a piece of
HTML code which is sent by the Web Server to our Browser, which in turn converts into the web
page.

Example :
import requests
import urllib
url="http://www.google.co.in"
webpage=urllib.request.urlopen(url)
print(webpage.read())

 Downloading a Web Page from Internet :


The following python program uses urllib module to download a webpage to a local folder. This
program downloads the webpage html content only, it doesn't download the linked images or
other resources.

Example :
import urllib.request
from urllib.error import URLError

target_file_path = "D:/downloaded.html" # downloaded page saved here


try:
response = urllib.request.urlopen('https://www.google.co.in/')
html_content = response.read()
with open(target_file_path,"wb") as fp:
fp.write(html_content)
except URLError as e:
print("Unable to download page: "+str(e.reason))

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)

 TCP/IP Server & TCP/IP Client :

 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)

# Activate the TCP server.


# To abort the TCP server, press Ctrl‐C.
tcp_server.serve_forever()

 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

host_ip, server_port = "127.0.0.1", 9999


data = " Hello how are you?\n"

# Initialize a TCP client socket using SOCK_STREAM


tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

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()

print ("Bytes Sent: {}".format(data))


print ("Bytes Received: {}".format(received.decode()))

 UDP Server & UDP Client :


UDP or user datagram protocol is an alternative protocol to its more common counterpart TCP.
UDP like TCP is a protocol for packet transfer from one host to another

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)

# Create a datagram socket


UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)

# Bind to address and ip


UDPServerSocket.bind((localIP, localPort))
print("UDP server up and listening")

# Listen for incoming datagrams


while(True):

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)

# Sending a reply to client


UDPServerSocket.sendto(bytesToSend, address)

 CLIENT :
Example :
import socket
msgFromClient = "Hello UDP Server"
bytesToSend = str.encode(msgFromClient)
serverAddressPort = ("127.0.0.1", 20001)
bufferSize = 1024

# Create a UDP socket at client side


UDPClientSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)

# Send to server using created UDP socket


UDPClientSocket.sendto(bytesToSend, serverAddressPort)
msgFromServer = UDPClientSocket.recvfrom(bufferSize)
msg = "Message from Server {}".format(msgFromServer[0])
print(msg)

 FTP Server & FTP Client :


File transfer is the process of copying or moving a file from one computer to another over a
network or Internet connection.
The basic idea is to create a server that listens on a particular port; this server will be responsible
for receiving files (you can make the server send files as well). On the other hand, the client will try
to connect to the server and send a file of any type.

 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 = socket.socket() # Create a socket object


host = socket.gethostname() # Get local machine name
port = 60000 # Reserve a port for your service.

s.connect((host, port))
msg='Hello Server'
byt=msg.encode()
s.send(byt)

with open('received_file.txt', 'wb') as f:


print('file opened')
while True:
print('receiving data...')
data = s.recv(1024)
print('data=%s', (data))
if not data:
break
# write data to a file
f.write(data)

f.close()
print('Successfully get the file')
s.close()
print('connection closed')

Page : 8

You might also like