unit 4 python
unit 4 python
Network Programming
Python plays an essential role in network programming. The standard library of Python has full
support for network protocols, encoding, and decoding of data and other networking concepts,
and it is simpler to write network programs in Python than that of C++.
Internet Protocol
These are the set of procedures or rules which govern the flow of data, format of data over the
internet. Mainly, we will be dealing with two major protocols over the internet:
• User Datagram Protocol(UDP)
• Transmission Control Protocol(TCP)
Now, coming up is some more detail about the IP addressess. IP address is of two types:
1. Private IP address: Ranges from (192.168.0.0 – 192.168.255.255), (172.16.0.0 –
172.31.255.255) or (10.0.0.0 - 10.255.255.255)
2. Public IP address: A public IP address is an IP address that your home or business router
receives from your ISP(Internet Service Provider).
1 Domain
The family of protocols that is used as the transport mechanism. These values are
constants such as AF_INET, PF_INET, PF_UNIX, PF_X25, and so on.
2 type
The type of communications between the two endpoints, typically SOCK_STREAM for
connection-oriented protocols and SOCK_DGRAM for connectionless protocols.
3 protocol
Typically zero, this may be used to identify a variant of a protocol within a domain and
type.
4 hostname
The identifier of a network interface −
• A string, which can be a host name, a dotted-quad address, or an IPV6 address
in colon (and possibly dot) notation
• A string "<broadcast>", which specifies an INADDR_BROADCAST address.
• A zero-length string, which specifies INADDR_ANY, or
• An Integer, interpreted as a binary address in host byte order.
5 port
Each server listens for clients calling on one or more ports. A port may be a Fixnum
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. We can use the socket module for socket programming. For this, we have to
include the socket module –
import socket
to create a socket we have to use the socket.socket() method.
Syntax:
socket.socket(socket_family, socket_type, protocol=0)
Where,
• socket_family: Either AF_UNIX or AF_INET
• socket_type: Either SOCK_STREAM or SOCK_DGRAM.
• protocol: Usually left out, defaulting to 0.
Example:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print(s)
output
<socket.socket fd=732, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM,
proto=0>
Once you have socket object, then you can use required functions to create your client or server
program. Following is the list of functions required −
1 s.bind()
This method binds address (hostname, port number pair) to socket.
2 s.listen()
This method sets up and start TCP listener.
3 s.accept()
This passively accept TCP client connection, waiting until connection arrives
(blocking).
1 s.connect()
1 s.recv()
This method receives TCP message
2 s.send()
This method transmits TCP message
3 s.recvfrom()
This method receives UDP message
4 s.sendto()
This method transmits UDP message
5 s.close()
This method closes socket
6 socket.gethostname()
Returns the hostname.
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).
Example
# Python Program to Get IP Address
import socket
hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)
print("Your Computer Name is:" + hostname)
print("Your Computer IP Address is:" + IPAddr)
What is urllib?
urllib is a Python module that can be used for opening URLs. It defines functions and classes to
help in URL actions.
With Python you can also access and retrieve data from the internet like XML, HTML, JSON,
etc. You can also use Python to work with this data directly. In this tutorial we are going to see
how we can retrieve data from the web.
Example
import urllib.request
webUrl = urllib.request.urlopen('https://christcollegerajkot.edu.in/Motto/')
print ("result code: " + str(webUrl.getcode()))
data = webUrl.read(1000)
print (data)
Installation
python -m pip install beautifulsoup4
Example
import urllib.request
from bs4 import BeautifulSoup
response = urllib.request.urlopen('file:///D://christ/kruti/sample.html')
html_doc = response.read()
# Parse the html file
soup = BeautifulSoup(html_doc, 'html.parser')
for x in soup.find_all('h1'):
print(x.string)
Downloading image
Example(png)
# imported the requests library
import requests
image_url = "https://www.python.org/static/community_logos/python-logo-master-v3-TM.png"
This small piece of code written above will download the following image from the web. Now
check your local directory(the folder where this script resides), and you will find this image:
All we need is the URL of the image source. (You can get the URL of image source by right-
clicking on the image and selecting the View Image option.)
Example
import requests
file_url =
"http://www.halvorsen.blog/documents/programming/python/resources/Python%20Programming
.pdf"
Example: tcp_server.py
import socket #line 1: Import socket module
s = socket.socket() #line 2: create a socket object
host = socket.gethostname() #line 3: Get current machine name
port = 9999 #line 4: Get port number for connection
s.bind((host,port)) #line 5: bind with the address
print ("Waiting for connection...")
s.listen(5) #line 6: listen for connections
msg="saying hi"
while True:
conn,addr = s.accept() #line 7: connect and accept from client
print ('Got Connection from', addr)
conn.send(b"saying hi")
conn.close() #line 8: Close the connection
Example: tcp_client.py
import socket
s = socket.socket()
host = socket.gethostname() # Get current machine name
port = 9999 # Client wants to connect to server's
# port number 9999
s.connect((host,port))
print (s.recv(1024)) # 1024 is bufsize or max amount
# of data to be received at once
s.close()
Now open terminal (cmd) and run the server script from the location you have saved the script:
C:\Users\programs> py tcp_server.py
Now open a new terminal (cmd) and run the client script from the location you have saved the
script:
C\Users\programs>py tcp_client.py
A UDP Server
Example: udpserver.py
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))
while(True):
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)
Example: udpclient.py
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)
File Server
Setup A Basic File server Using simpleHTTPserver:
Just run the following command from your Terminal to start the file server:
$ python -m http.server 8000
That's it. File server is ready. Open the web browser and type:
localhost:8000/
We will design both server and client model so that each can communicate with them. The steps
can be considered like this.
1. Python socket server program executes at first and wait for any request
2. Python socket client program will initiate the conversation at first.
3. Then server program will response accordingly to client requests.
4. Client program will terminate if user enters “bye” message. Server program will also
terminate when client program terminates, this is optional and we can keep server
program running indefinitely or terminate with some specific command in client request.
Example: socket_server.py
import socket
def server_program():
# get the hostname
host = socket.gethostname()
port = 5000 # initiate port no above 1024
server_program()
So our python socket server is running on port 5000 and it will wait for client request. If you
want server to not quit when client connection is closed, just remove the if condition and break
statement. Python while loop is used to run the server program indefinitely and keep waiting for
client request.
Example:socket_client.py
import socket
def client_program():
host = socket.gethostname() # as both code is running on same pc
port = 5000 # socket server port number
client_program()
You can test email functionality by running a local SMTP debugging server, using
the smtpd module that comes pre-installed with Python. Rather than sending emails to the
specified address, it discards them and prints their content to the console. Running a local
debugging server means it’s not necessary to deal with encryption of messages or use credentials
to log in to an email server.
You can start a local SMTP debugging server by typing the following in Command Prompt:
python -m smtpd -c DebuggingServer -n localhost:1025
Any emails sent through this server will be discarded and shown in the terminal window as
a bytes object for each line.
Example
import smtplib
sender = '[email protected]'
receivers = ['[email protected]']
message = """From: From Kruti <[email protected]>
To: To Tosha <[email protected]>
Subject: SMTP e-mail test
Output:
On Python Shell :
Successfully sent email
On CMD:
---------- MESSAGE FOLLOWS ----------
b'From: From Kruti <[email protected]>'
b'To: To Tosha <[email protected]>'
b'Subject: SMTP e-mail test'
b'X-Peer: ::1'
b''
b'This is a test e-mail message.'
------------ END MESSAGE ------------
“smtplib” creates a Simple Mail Transfer Protocol client session object which is used to send
emails to any valid email id on the internet. Different websites use different port numbers.
We are using a Gmail account to send a mail. Port number used here is ‘587’. And if you want to
send mail using a website other than Gmail, you need to get the corresponding information.
Steps to send mail from Gmail account:
1. First of all, “smtplib” library needs to be imported.
2. After that, to create a session, we will be using its instance SMTP to encapsulate an
SMTP connection.
s = smtplib.SMTP('smtp.gmail.com', 587)
In this, you need to pass the first parameter of the server location and the second parameter of the
port to use. For Gmail, we use port number 587.
3. For security reasons, now put the SMTP connection in the TLS mode. TLS (Transport
Layer Security) encrypts all the SMTP commands. After that, for security and
authentication, you need to pass your Gmail account credentials in the login instance.The
compiler will show an authentication error if you enter invalid email id or password.
4. Store the message you need to send in a variable say, message. Using the sendmail()
instance, send your message. sendmail() uses three parameters: sender_email_id,
receiver_email_id and message_to_be_sent. The parameters need to be in the same
sequence.
This will send the email from your account. After you have completed your task, terminate the
SMTP session by using quit().
Example
# Python code to illustrate Sending mail from your Gmail account
import smtplib
# Authentication
s.login("sender_email_id", "sender_email_id_password")
# message to be sent
message = "Message_you_need_to_send"
GUI Programming
A graphical user interface (GUI) allows a user to interact with a computer program using a
pointing device that manipulates small pictures on a computer screen. The small pictures are
called icons or widgets. Various types of pointing devices can be used, such as a mouse, a stylus
pen, or a human finger on a touch screen.
There are two main methods used which the user needs to remember while creating the Python
application with GUI.
1. Tk(screenName=None, baseName=None, className=’Tk’, useTk=1): To create a main
window, tkinter offers a method ‘Tk(screenName=None, baseName=None,
className=’Tk’, useTk=1)’. To change the name of the window, you can change the
className to the desired one. The basic code used to create the main window of the
application is:
m=tkinter.Tk() #where m is the name of the main window object
2. mainloop(): There is a method known by the name mainloop() is used when your application
is ready to run. mainloop() is an infinite loop used to run the application, wait for an event to
occur and process the event as long as the window is not closed.
m.mainloop()
Example:
import tkinter
m = tkinter.Tk()
'''
widgets are added here
'''
m.mainloop()
Tkinter Widgets
Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI
application. These controls are commonly called widgets. There are a number of widgets which
you can put in your tkinter application.
1 Button
The Button widget is used to display buttons in your application.
2 Canvas
The Canvas widget is used to draw shapes, such as lines, ovals, polygons and
rectangles, in your application.
3 Checkbutton
The Checkbutton widget is used to display a number of options as checkboxes. The user
can select multiple options at a time.
4 Entry
The Entry widget is used to display a single-line text field for accepting values from a
user.
5 Frame
The Frame widget is used as a container widget to organize other widgets.
6 Label
The Label widget is used to provide a single-line caption for other widgets. It can also
contain images.
7 Listbox
The Listbox widget is used to provide a list of options to a user.
8 Menubutton
The Menubutton widget is used to display menus in your application.
9 Menu
The Menu widget is used to provide various commands to a user. These commands are
contained inside Menubutton.
10 Message
The Message widget is used to display multiline text fields for accepting values from a
user.
11 Radiobutton
The Radiobutton widget is used to display a number of options as radio buttons. The
user can select only one option at a time.
12 Scale
The Scale widget is used to provide a slider widget.
13 Scrollbar
The Scrollbar widget is used to add scrolling capability to various widgets, such as list
boxes.
14 Text
The Text widget is used to display text in multiple lines.
15 Toplevel
The Toplevel widget is used to provide a separate window container.
16 Spinbox
The Spinbox widget is a variant of the standard Tkinter Entry widget, which can be
used to select from a fixed number of values.
17 PanedWindow
A PanedWindow is a container widget that may contain any number of panes, arranged
horizontally or vertically.
18 LabelFrame
A labelframe is a simple container widget. Its primary purpose is to act as a spacer or
container for complex window layouts.
19 tkMessageBox
This module is used to display message boxes in your applications.
Button
To add a button in your application, this widget is used.
The general syntax is:
w=Button(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the Buttons. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
• activebackground: to set the background color when button is under the cursor.
• activeforeground: to set the foreground color when button is under the cursor.
• bg: to set he normal background color.
• command: to call a function.
• font: to set the font on the button label.
• image: to set the image on the button.
• width: to set the width of the button.
• height: to set the height of the button
Example
import tkinter as tk
r = tk.Tk()
r.title('Counting Seconds')
button = tk.Button(r, text='Stop', width=25, command=r.destroy)
button.pack()
r.mainloop()
Label
It refers to the display box where you can put any text or image which can be updated any time
as per the code.
The general syntax is:
w=Label(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
• bg: to set the normal background color.
• command: to call a function.
• font: to set the font on the button label.
• image: to set the image on the button.
• width: to set the width of the button.
• Height: to set the height of the button.
Example
from tkinter import *
root = Tk()
w = Label(root, text='This is label',bg="red",height=20,width=30)
w.pack()
root.mainloop()
Entry
It is used to input the single line text entry from the user.. For multi-line text input, Text widget is
used.
The general syntax is:
w=Entry(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
• bd: to set the border width in pixels.
• bg: to set the normal background color.
• cursor: to set the cursor used.
• command: to call a function.
• highlightcolor: to set the color shown in the focus highlight.
• width: to set the width of the button.
• height: to set the height of the button.
Example
from tkinter import *
master = Tk()
Label(master, text='First Name').grid(row=0,column=0)
Label(master, text='Last Name').grid(row=0,column=2)
e1 = Entry(master,bd=5)
e2 = Entry(master,bg="pink")
e1.grid(row=0, column=1)
e2.grid(row=0, column=3)
mainloop()
Frame
It acts as a container to hold the widgets. It is used for grouping and organizing the widgets. The
general syntax is:
w = Frame(master, option=value)
master is the parameter used to represent the parent window.
There are number of options which are used to change the format of the widget. Number of
options can be passed as parameters separated by commas. Some of them are listed below.
• highlightcolor: To set the color of the focus highlight when widget has to be focused.
• bd: to set the border width in pixels.
• bg: to set the normal background color.
• cursor: to set the cursor used.
• width: to set the width of the widget.
• height: to set the height of the widget.
Example
from tkinter import *
root = Tk()
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
redbutton = Button(frame, text = 'Red', fg ='red')
redbutton.pack( side = LEFT)
greenbutton = Button(frame, text = 'Brown', fg='brown')
greenbutton.pack( side = LEFT )
bluebutton = Button(frame, text ='Blue', fg ='blue')
bluebutton.pack( side = LEFT )
blackbutton = Button(bottomframe, text ='Black', fg ='black')
blackbutton.pack( side = BOTTOM)
root.mainloop()
Messagebox
The message dialogues are provided by the 'messagebox' submodule of tkinter.
'messagebox' consists of the following functions, which correspond to dialog windows:
• askokcancel(title=None, message=None, **options)
Ask if operation should proceed; return true if the answer is ok
• askquestion(title=None, message=None, **options)
Ask a question
• askretrycancel(title=None, message=None, **options)
Ask if operation should be retried; return true if the answer is yes
• askyesno(title=None, message=None, **options)
Ask a question; return true if the answer is yes
• askyesnocancel(title=None, message=None, **options)
Ask a question; return true if the answer is yes, None if cancelled.
• showerror(title=None, message=None, **options)
Show an error message
• showinfo(title=None, message=None, **options)
Show an info message
• showwarning(title=None, message=None, **options)
Show a warning message
Example
from tkinter import messagebox
messagebox.showinfo("Information","Informative message")
messagebox.showerror("Error", "Error message")
messagebox.showwarning("Warning","Warning message")
Yes/No Questions
The tkinter messagebox object also allows you to ask a user simple yes/no type questions and
varies the button names based on the type of question. These functions are:
Example
from tkinter import messagebox
answer = messagebox.askokcancel("Question","Do you want to open this file?")
print(answer)
answer = messagebox.askretrycancel("Question", "Do you want to try that again?")
print(answer)
answer = messagebox.askyesno("Question","Do you like Python?")
print(answer)
answer = messagebox.askyesnocancel("Question", "Continue playing?")
print(answer)
The return value is a Boolean, True or False, answer to the question. If “cancel” is an option and
the user selects the “cancel” button, None is returned.
Example
import tkinter as tk
from tkinter import simpledialog
application_window = tk.Tk()
minvalue=0.0, maxvalue=100000.0)
if answer is not None:
print("Your salary is ", answer)
else:
print("You don't have a salary?")
File Chooser
A common task is to select the names of folders and files on a storage device. This can be
accomplished using a filedialog object. Note that these commands do not save or load a file.
They simply allow a user to select a file. Once you have the file name, you can open, process,
and close the file using appropriate Python code. These dialog boxes always return you a “fully
qualified file name” that includes a full path to the file. Also note that if a user is allowed to
select multiple files, the return value is a tuple that contains all of the selected files. If a user
cancels the dialog box, the returned value is an empty string.
Example
import tkinter as tk
from tkinter import filedialog
import os
application_window = tk.Tk()
# Build a list of tuples for each file type the file dialog should display
my_filetypes = [('all files', '.*'), ('text files', '.txt')]
print(answer)
Color Chooser
Tkinter includes a nice dialog box for choosing colors. You provide it with a parent window and
an initial color, and it returns a color in two different specifications: 1) a RGB value as a tuple,
such as (255, 0, 0) which represents red, and 2) a hexadecimal string used in web pages, such
as "#FF0000" which also represents red. If the user cancels the operation, the return values
are None and None.
Example
import tkinter as tk
from tkinter.colorchooser import askcolor
def callback():
result = askcolor(color="#6A9662",
title = "Bernd's Colour Chooser")
print(result)
root = tk.Tk()
tk.Button(root,
text='Choose Color',
fg="darkgreen",
command=callback).pack(side=tk.LEFT, padx=10)
tk.Button(text='Quit',
command=root.quit,
fg="red").pack(side=tk.LEFT, padx=10)
tk.mainloop()