SlideShare a Scribd company logo
1 of 27
Download to read offline
NETWORK PROGRAMMING
USING PYTHON
ALI NEZHAD
OUTLINE
• Data Communications Fundamentals
• Sockets
• Python support for sockets
• TCP and UDP communication examples
• Higher level programming in Python
2
TCP/IP MODEL
NETWORK
Client
ServerRequest
Response
3
DATA ENCAPSULATION
4
SSH
SMTP
FTP
TRANSPORT LAYER
• Provides service to
application layer.
• Multiplexes applications.
• TCP does much more.
• Most applications use TCP.
• UDP for real-time or tolerant
applications.
TCP 5
Source: Data and Computer Communications (Stallings)
TCP OPERATION
6
Source: Data and Computer Communications (Stallings)
TCP VS. UDP
7
Source: Data and Computer Communications (Stallings)
IP PACKET
8
Source: Data and Computer Communications (Stallings)
SOCKETS
• Endpoints of a bidirectional communication channel
• Used to address an application on a machine.
• Allow multiplexing of applications.
• Identified by combination: IP_address + protocol + port_no.
• Servers use the well-known port numbers (0 - 1023).
• Clients use the ephemeral port numbers (1024 - 65535).
• Can be treated as files.
9
SOCKET MODULE IN PYTHON
• Used in low-level network programming
• Usually used by higher level APIs.
• Functions correspond to UNIX system calls.
• Except makefile()
• Examples: socket(), bind(), listen(), accept(), connect(), send(), recv(), close()
• Attributes
• family, type, proto
• Used to create socket objects.
• s = socket.socket( family, type, proto) 10
A subtype, usually
0.
SOCKET ATTRIBUTES
ADDRESS FAMILY
• Identifies the domain and a family of protocols
• Options for the address family of the socket:
• AF_UNIX: a single string for UNIX
• Represented by socket.AF_UNIX constant
• Addres is just a filename.
• AF_INET: a pair of (host, port) for IPv4
• Represented by socket.AF_INET constant
• (‘www.yahoo.com’, 80)
• (‘209.191.88.254’, 80)
• AF_INET6: quadtuple of (host, port, flowid, scopeid) for IPv6
• Represented by socket.AF_INET6 constant 11
SOCKET ATTRIBUTES
TYPE
• Commonly used types:
• socket.SOCK_STREAM (for TCP sockets, connection-oriented)
• socket.SOCK_DGRAM (for UDP sockets, connectionless)
12
SERVER
TCP
13
import socket
HOST = ‘ ' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
Source: docs.python.org
Would be 80
for a web
server.
SERVER (CONTINUED)
TCP
14
import socket
HOST = ‘ ' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
Source: docs.python.org
SERVER (CONTINUED)
TCP
15
import socket
HOST = ‘ ' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
Source: docs.python.org
SERVER (CONTINUED)
TCP
16
import socket
HOST = ‘ ' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
Source: docs.python.org
SERVER (CONTINUED)
TCP
17
import socket
HOST = ‘ ' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
Source: docs.python.org
SERVER (CONTINUED)
TCP
18
import socket
HOST = ‘ ' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.sendall(data)
conn.close()
Source: docs.python.org
CLIENT
TCP
import socket
HOST = 'daring.cwi.nl' # The remote host
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
19
Source: docs.python.org
No need to
specify local
socket.
CLIENT (CONTINUED)
TCP
import socket
HOST = 'daring.cwi.nl' # The remote host
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)
20
Source: docs.python.org
Could be an HTTP request like
(‘GET /index.html HTTP/1.0
nn ’).
Transport layer gives service to
application layer.
SERVER
UDP
21
Source: www.dabeas.com
CLIENT
UDP
22
Source: www.dabeas.com
HIGH LEVEL NETWORK PROGRAMMING
• Support for specific applications e.g. HTTP, FTP, …
• Instead of socket module, servers use other modules and libraries, e.g.:
• HTTP: httplib, urllib2, xmllib
• FTP: ftplib, urllib
• SMTP: smtplib
• Servers usually use the SocketServer module.
• Different file formats and encodings must be handled at the client using
various libraries such as csv, htmlparser and json. 23
SOCKETSERVER EXAMPLE
TIME SERVER
24
import SocketServer
import time
Class TimeHandler(SocketServer.BaseRequestHandler):
def handle(self):
self.request.sendall(time.ctime()+"n")
serv = SocketServer.TCPServer(("",8000),TimeHandler)
serv.serve_forever()
Source: www.dabeas.com
APPLICATION LAYER
HTTP EXAMPLE
• Opening a web page:
25
import urllib2
u = urllib2.urlopen("http://www.python/org/index.html")
data = u.read()
print data
SUMMARY
• Client/server communication model
• TCP and UDP give service to applications.
• Use TCP sockets if you need reliability.
• A socket identifies a single PID on a single machine.
• Use the socket module to create and use socket objects.
• Python includes many other higher-level networking modules.
26
27

More Related Content

What's hot

Socket programming
Socket programmingSocket programming
Socket programmingharsh_bca06
 
Socket programming
Socket programmingSocket programming
Socket programmingAnurag Tomar
 
Application Layer and Socket Programming
Application Layer and Socket ProgrammingApplication Layer and Socket Programming
Application Layer and Socket Programmingelliando dias
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sksureshkarthick37
 
How do I construct a python web server using this code? #import socket modul...
How do I construct a python web server using this code?  #import socket modul...How do I construct a python web server using this code?  #import socket modul...
How do I construct a python web server using this code? #import socket modul...hwbloom25
 
Socket programming using java
Socket programming using javaSocket programming using java
Socket programming using javaUC San Diego
 
Opentalk at Large - StS 2005
Opentalk at Large - StS 2005Opentalk at Large - StS 2005
Opentalk at Large - StS 2005Martin Kobetic
 
Programming TCP/IP with Sockets
Programming TCP/IP with SocketsProgramming TCP/IP with Sockets
Programming TCP/IP with Socketselliando dias
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket ProgrammingVipin Yadav
 
Python Network Programming – Course Applications Guide
Python Network Programming – Course Applications GuidePython Network Programming – Course Applications Guide
Python Network Programming – Course Applications GuideMihai Catalin Teodosiu
 

What's hot (20)

Socket programming in c
Socket programming in cSocket programming in c
Socket programming in c
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Lecture10
Lecture10Lecture10
Lecture10
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Application Layer and Socket Programming
Application Layer and Socket ProgrammingApplication Layer and Socket Programming
Application Layer and Socket Programming
 
Ppt of socket
Ppt of socketPpt of socket
Ppt of socket
 
socket programming
socket programming socket programming
socket programming
 
Socket.io v.0.8.3
Socket.io v.0.8.3Socket.io v.0.8.3
Socket.io v.0.8.3
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sk
 
Network Sockets
Network SocketsNetwork Sockets
Network Sockets
 
Socket System Calls
Socket System CallsSocket System Calls
Socket System Calls
 
How do I construct a python web server using this code? #import socket modul...
How do I construct a python web server using this code?  #import socket modul...How do I construct a python web server using this code?  #import socket modul...
How do I construct a python web server using this code? #import socket modul...
 
Socket programming using java
Socket programming using javaSocket programming using java
Socket programming using java
 
Socket programming
Socket programming Socket programming
Socket programming
 
Opentalk at Large - StS 2005
Opentalk at Large - StS 2005Opentalk at Large - StS 2005
Opentalk at Large - StS 2005
 
Programming TCP/IP with Sockets
Programming TCP/IP with SocketsProgramming TCP/IP with Sockets
Programming TCP/IP with Sockets
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket Programming
 
Python Network Programming – Course Applications Guide
Python Network Programming – Course Applications GuidePython Network Programming – Course Applications Guide
Python Network Programming – Course Applications Guide
 

Similar to Python Network Programming Guide

INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.pptINTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.pptsenthilnathans25
 
Network Prog.ppt
Network Prog.pptNetwork Prog.ppt
Network Prog.pptEloOgardo
 
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونیاسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونیMohammad Reza Kamalifard
 
Sockets in unix
Sockets in unixSockets in unix
Sockets in unixswtjerin4u
 
Raspberry pi Part 23
Raspberry pi Part 23Raspberry pi Part 23
Raspberry pi Part 23Techvilla
 
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYAPYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYAMaulik Borsaniya
 
How to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking NeedsHow to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking NeedsDigitalOcean
 

Similar to Python Network Programming Guide (20)

sockets_intro.ppt
sockets_intro.pptsockets_intro.ppt
sockets_intro.ppt
 
Sockets intro
Sockets introSockets intro
Sockets intro
 
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.pptINTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
 
lab04.pdf
lab04.pdflab04.pdf
lab04.pdf
 
Sockets
Sockets Sockets
Sockets
 
Basic socket programming
Basic socket programmingBasic socket programming
Basic socket programming
 
Network Prog.ppt
Network Prog.pptNetwork Prog.ppt
Network Prog.ppt
 
Net Programming.ppt
Net Programming.pptNet Programming.ppt
Net Programming.ppt
 
Sockets
Sockets Sockets
Sockets
 
123
123123
123
 
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونیاسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
 
Sockets in unix
Sockets in unixSockets in unix
Sockets in unix
 
Os 2
Os 2Os 2
Os 2
 
Pemrograman Jaringan
Pemrograman JaringanPemrograman Jaringan
Pemrograman Jaringan
 
Raspberry pi Part 23
Raspberry pi Part 23Raspberry pi Part 23
Raspberry pi Part 23
 
Basics of sockets
Basics of socketsBasics of sockets
Basics of sockets
 
L5-Sockets.pptx
L5-Sockets.pptxL5-Sockets.pptx
L5-Sockets.pptx
 
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYAPYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
 
How to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking NeedsHow to Leverage Go for Your Networking Needs
How to Leverage Go for Your Networking Needs
 
03 sockets
03 sockets03 sockets
03 sockets
 

More from Ali Nezhad

Internet of things
Internet of thingsInternet of things
Internet of thingsAli Nezhad
 
converged Networks
converged Networksconverged Networks
converged NetworksAli Nezhad
 
cnet311 q-bank
cnet311 q-bankcnet311 q-bank
cnet311 q-bankAli Nezhad
 
IP Addressing and subnetting
IP Addressing and subnettingIP Addressing and subnetting
IP Addressing and subnettingAli Nezhad
 
Setting up a WiFi Network v3
Setting up a WiFi Network v3Setting up a WiFi Network v3
Setting up a WiFi Network v3Ali Nezhad
 
adhoc network workshop
adhoc network workshopadhoc network workshop
adhoc network workshopAli Nezhad
 

More from Ali Nezhad (6)

Internet of things
Internet of thingsInternet of things
Internet of things
 
converged Networks
converged Networksconverged Networks
converged Networks
 
cnet311 q-bank
cnet311 q-bankcnet311 q-bank
cnet311 q-bank
 
IP Addressing and subnetting
IP Addressing and subnettingIP Addressing and subnetting
IP Addressing and subnetting
 
Setting up a WiFi Network v3
Setting up a WiFi Network v3Setting up a WiFi Network v3
Setting up a WiFi Network v3
 
adhoc network workshop
adhoc network workshopadhoc network workshop
adhoc network workshop
 

Recently uploaded

6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroomSamsung Business USA
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxAnupam32727
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptxmary850239
 
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...Nguyen Thanh Tu Collection
 
How to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineHow to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineCeline George
 
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...Osopher
 
18. Training and prunning of horicultural crops.pptx
18. Training and prunning of horicultural crops.pptx18. Training and prunning of horicultural crops.pptx
18. Training and prunning of horicultural crops.pptxUmeshTimilsina1
 
The Emergence of Legislative Behavior in the Colombian Congress
The Emergence of Legislative Behavior in the Colombian CongressThe Emergence of Legislative Behavior in the Colombian Congress
The Emergence of Legislative Behavior in the Colombian CongressMaria Paula Aroca
 
LEVERAGING SYNERGISM INDUSTRY-ACADEMIA PARTNERSHIP FOR IMPLEMENTATION OF NAT...
LEVERAGING SYNERGISM INDUSTRY-ACADEMIA PARTNERSHIP FOR IMPLEMENTATION OF  NAT...LEVERAGING SYNERGISM INDUSTRY-ACADEMIA PARTNERSHIP FOR IMPLEMENTATION OF  NAT...
LEVERAGING SYNERGISM INDUSTRY-ACADEMIA PARTNERSHIP FOR IMPLEMENTATION OF NAT...pragatimahajan3
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptxmary850239
 
Employablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxEmployablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxryandux83rd
 
How to create _name_search function in odoo 17
How to create _name_search function in odoo 17How to create _name_search function in odoo 17
How to create _name_search function in odoo 17Celine George
 
Shark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristicsShark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristicsArubSultan
 
ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6Vanessa Camilleri
 
BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 11 (CẢ NĂM) - FRIENDS GLOBAL - NĂM HỌC...
BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 11 (CẢ NĂM) - FRIENDS GLOBAL - NĂM HỌC...BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 11 (CẢ NĂM) - FRIENDS GLOBAL - NĂM HỌC...
BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 11 (CẢ NĂM) - FRIENDS GLOBAL - NĂM HỌC...Nguyen Thanh Tu Collection
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...Nguyen Thanh Tu Collection
 
Advancing Gender Equality The Crucial Role of Science and Technology 4 April ...
Advancing Gender Equality The Crucial Role of Science and Technology 4 April ...Advancing Gender Equality The Crucial Role of Science and Technology 4 April ...
Advancing Gender Equality The Crucial Role of Science and Technology 4 April ...EduSkills OECD
 

Recently uploaded (20)

6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom6 ways Samsung’s Interactive Display powered by Android changes the classroom
6 ways Samsung’s Interactive Display powered by Android changes the classroom
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
 
Chi-Square Test Non Parametric Test Categorical Variable
Chi-Square Test Non Parametric Test Categorical VariableChi-Square Test Non Parametric Test Categorical Variable
Chi-Square Test Non Parametric Test Categorical Variable
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx
 
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
 
Spearman's correlation,Formula,Advantages,
Spearman's correlation,Formula,Advantages,Spearman's correlation,Formula,Advantages,
Spearman's correlation,Formula,Advantages,
 
How to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineHow to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command Line
 
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
Healthy Minds, Flourishing Lives: A Philosophical Approach to Mental Health a...
 
18. Training and prunning of horicultural crops.pptx
18. Training and prunning of horicultural crops.pptx18. Training and prunning of horicultural crops.pptx
18. Training and prunning of horicultural crops.pptx
 
The Emergence of Legislative Behavior in the Colombian Congress
The Emergence of Legislative Behavior in the Colombian CongressThe Emergence of Legislative Behavior in the Colombian Congress
The Emergence of Legislative Behavior in the Colombian Congress
 
LEVERAGING SYNERGISM INDUSTRY-ACADEMIA PARTNERSHIP FOR IMPLEMENTATION OF NAT...
LEVERAGING SYNERGISM INDUSTRY-ACADEMIA PARTNERSHIP FOR IMPLEMENTATION OF  NAT...LEVERAGING SYNERGISM INDUSTRY-ACADEMIA PARTNERSHIP FOR IMPLEMENTATION OF  NAT...
LEVERAGING SYNERGISM INDUSTRY-ACADEMIA PARTNERSHIP FOR IMPLEMENTATION OF NAT...
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx
 
Israel Genealogy Research Assoc. April 2024 Database Release
Israel Genealogy Research Assoc. April 2024 Database ReleaseIsrael Genealogy Research Assoc. April 2024 Database Release
Israel Genealogy Research Assoc. April 2024 Database Release
 
Employablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxEmployablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptx
 
How to create _name_search function in odoo 17
How to create _name_search function in odoo 17How to create _name_search function in odoo 17
How to create _name_search function in odoo 17
 
Shark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristicsShark introduction Morphology and its behaviour characteristics
Shark introduction Morphology and its behaviour characteristics
 
ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6ICS 2208 Lecture Slide Notes for Topic 6
ICS 2208 Lecture Slide Notes for Topic 6
 
BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 11 (CẢ NĂM) - FRIENDS GLOBAL - NĂM HỌC...
BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 11 (CẢ NĂM) - FRIENDS GLOBAL - NĂM HỌC...BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 11 (CẢ NĂM) - FRIENDS GLOBAL - NĂM HỌC...
BÀI TẬP BỔ TRỢ 4 KĨ NĂNG TIẾNG ANH LỚP 11 (CẢ NĂM) - FRIENDS GLOBAL - NĂM HỌC...
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
BÀI TẬP BỔ TRỢ TIẾNG ANH 11 THEO ĐƠN VỊ BÀI HỌC - CẢ NĂM - CÓ FILE NGHE (GLOB...
 
Advancing Gender Equality The Crucial Role of Science and Technology 4 April ...
Advancing Gender Equality The Crucial Role of Science and Technology 4 April ...Advancing Gender Equality The Crucial Role of Science and Technology 4 April ...
Advancing Gender Equality The Crucial Role of Science and Technology 4 April ...
 

Python Network Programming Guide

  • 2. OUTLINE • Data Communications Fundamentals • Sockets • Python support for sockets • TCP and UDP communication examples • Higher level programming in Python 2
  • 5. SSH SMTP FTP TRANSPORT LAYER • Provides service to application layer. • Multiplexes applications. • TCP does much more. • Most applications use TCP. • UDP for real-time or tolerant applications. TCP 5 Source: Data and Computer Communications (Stallings)
  • 6. TCP OPERATION 6 Source: Data and Computer Communications (Stallings)
  • 7. TCP VS. UDP 7 Source: Data and Computer Communications (Stallings)
  • 8. IP PACKET 8 Source: Data and Computer Communications (Stallings)
  • 9. SOCKETS • Endpoints of a bidirectional communication channel • Used to address an application on a machine. • Allow multiplexing of applications. • Identified by combination: IP_address + protocol + port_no. • Servers use the well-known port numbers (0 - 1023). • Clients use the ephemeral port numbers (1024 - 65535). • Can be treated as files. 9
  • 10. SOCKET MODULE IN PYTHON • Used in low-level network programming • Usually used by higher level APIs. • Functions correspond to UNIX system calls. • Except makefile() • Examples: socket(), bind(), listen(), accept(), connect(), send(), recv(), close() • Attributes • family, type, proto • Used to create socket objects. • s = socket.socket( family, type, proto) 10 A subtype, usually 0.
  • 11. SOCKET ATTRIBUTES ADDRESS FAMILY • Identifies the domain and a family of protocols • Options for the address family of the socket: • AF_UNIX: a single string for UNIX • Represented by socket.AF_UNIX constant • Addres is just a filename. • AF_INET: a pair of (host, port) for IPv4 • Represented by socket.AF_INET constant • (‘www.yahoo.com’, 80) • (‘209.191.88.254’, 80) • AF_INET6: quadtuple of (host, port, flowid, scopeid) for IPv6 • Represented by socket.AF_INET6 constant 11
  • 12. SOCKET ATTRIBUTES TYPE • Commonly used types: • socket.SOCK_STREAM (for TCP sockets, connection-oriented) • socket.SOCK_DGRAM (for UDP sockets, connectionless) 12
  • 13. SERVER TCP 13 import socket HOST = ‘ ' # Symbolic name meaning all available interfaces PORT = 50007 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.sendall(data) conn.close() Source: docs.python.org Would be 80 for a web server.
  • 14. SERVER (CONTINUED) TCP 14 import socket HOST = ‘ ' # Symbolic name meaning all available interfaces PORT = 50007 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.sendall(data) conn.close() Source: docs.python.org
  • 15. SERVER (CONTINUED) TCP 15 import socket HOST = ‘ ' # Symbolic name meaning all available interfaces PORT = 50007 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.sendall(data) conn.close() Source: docs.python.org
  • 16. SERVER (CONTINUED) TCP 16 import socket HOST = ‘ ' # Symbolic name meaning all available interfaces PORT = 50007 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.sendall(data) conn.close() Source: docs.python.org
  • 17. SERVER (CONTINUED) TCP 17 import socket HOST = ‘ ' # Symbolic name meaning all available interfaces PORT = 50007 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.sendall(data) conn.close() Source: docs.python.org
  • 18. SERVER (CONTINUED) TCP 18 import socket HOST = ‘ ' # Symbolic name meaning all available interfaces PORT = 50007 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print 'Connected by', addr while 1: data = conn.recv(1024) if not data: break conn.sendall(data) conn.close() Source: docs.python.org
  • 19. CLIENT TCP import socket HOST = 'daring.cwi.nl' # The remote host PORT = 50007 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.sendall('Hello, world') data = s.recv(1024) s.close() print 'Received', repr(data) 19 Source: docs.python.org No need to specify local socket.
  • 20. CLIENT (CONTINUED) TCP import socket HOST = 'daring.cwi.nl' # The remote host PORT = 50007 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.sendall('Hello, world') data = s.recv(1024) s.close() print 'Received', repr(data) 20 Source: docs.python.org Could be an HTTP request like (‘GET /index.html HTTP/1.0 nn ’). Transport layer gives service to application layer.
  • 23. HIGH LEVEL NETWORK PROGRAMMING • Support for specific applications e.g. HTTP, FTP, … • Instead of socket module, servers use other modules and libraries, e.g.: • HTTP: httplib, urllib2, xmllib • FTP: ftplib, urllib • SMTP: smtplib • Servers usually use the SocketServer module. • Different file formats and encodings must be handled at the client using various libraries such as csv, htmlparser and json. 23
  • 24. SOCKETSERVER EXAMPLE TIME SERVER 24 import SocketServer import time Class TimeHandler(SocketServer.BaseRequestHandler): def handle(self): self.request.sendall(time.ctime()+"n") serv = SocketServer.TCPServer(("",8000),TimeHandler) serv.serve_forever() Source: www.dabeas.com
  • 25. APPLICATION LAYER HTTP EXAMPLE • Opening a web page: 25 import urllib2 u = urllib2.urlopen("http://www.python/org/index.html") data = u.read() print data
  • 26. SUMMARY • Client/server communication model • TCP and UDP give service to applications. • Use TCP sockets if you need reliability. • A socket identifies a single PID on a single machine. • Use the socket module to create and use socket objects. • Python includes many other higher-level networking modules. 26
  • 27. 27