SlideShare a Scribd company logo
Network Programming
Using Python
Contents
● Sockets
● Socket Types
● Python socket module
● Socket Object Methods
● Applications
○ Echo Server
○ Network Sniffer
○ File Transfer
Sockets
● The endpoints of a network connection
● Each host has a unique IP address
● Each service runs on a specific port
● Each connection is maintained on both
ends by a socket
● Sockets API allows us to send and receive
data
● Programming Languages provide modules
and classes to use this API
Socket Types
● Stream Sockets (SOCK_STREAM):
○ Connection-oriented
○ Use TCP
● Datagram Sockets (SOCK_DGRAM):
○ Connectionless
○ Use UDP
● Other types:
○ E.g. Raw Sockets
● We will use stream sockets
Python socket module
● socket.socket(family, type, proto)
○ Create new socket object
● socket.SOCK_STREAM (default)
● socket.SOCK_DGRAM
● socket.gethostname()
○ returns a string containing host name of the machine
● socket.gethostbyname(hostname)
○ Translates hostname to ip address
● socket.gethostbyaddr(ip_address)
○ Translates ip address to host name
Process
Socket Object Methods (Server)
● socket.bind(address)
○ e.g. socket.bind((host, port))
● socket.listen(backlog)
○ backlog specifies wait queue size
○ e.g. socket.listen(5)
● socket.accept()
○ Blocks until a client makes a connection
○ Returns (conn, address) where conn is a new socket object usable to send and receive data
○ address is the address bound to the socket on the other end of the connection
Socket Object Methods
● socket.connect(address) - used by client
○ e.g. socket.connect((host, port))
● socket.send(bytes, flags)
○ e.g. socket.send(b‘Hello, World!’)
● socket.recv(bufsize, flags)
○ e.g. socket.recv(1024)
○ bufsize specify maximum amount of data in bytes to be received at once
● socket.close()
○ close connection
Example 1: Echo Server
# Echo server program
import socket
HOST = socket.gethostname()
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 True:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()
Example 1: Echo Server
# Echo client program
import socket
HOST = 'localhost'
PORT = 50007 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(b'Hello, world')
data = s.recv(1024)
s.close()
print('Received', repr(data))
Example 2: Basic Network Sniffer
#Packet sniffer in python
#For Linux
import socket
#create an INET, raw socket
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP)
# receive a packet
while True:
print s.recvfrom(65565)
Full Example with Packet Parsing
Example 3: File Transfer
# file_transfer_server.py
import socket
host = socket.gethostname()
port = 6000
s = socket.socket()
s.bind((host, port))
s.listen(5)
print('Server listening..')
...
Example 3: File Transfer
# file_transfer_server.py
...
while True:
conn, addr = s.accept()
print('New Connection from {}'.format(addr))
with open('test.txt', 'r') as f:
while True:
l = f.read(1024)
if not l: break
conn.send(l.encode())
print('Sent {}'.format(l))
print('Finished Sending.')
conn.close()
print('Connection closed')
Example 3: File Transfer
# file_transfer_client.py
import socket # Import socket module
s = socket.socket() # Create a socket object
host = ‘localhost’ # Get local machine name
port = 6000 # Reserve a port for your service.
s.connect((host, port))
with open('received.txt', 'w') as f:
print('Downloading file..')
while True:
data = s.recv(1024)
if not data: break
f.write(data.decode())
print('Received: {}n'.format(data.decode()))
print('File downloaded successfully.')
s.close() # Close the socket when done
print('Connection closed')
Code
The previous examples and more can be found at:
https://github.com/ksonbol/socket_examples
Useful Resources
● Python socket module documentation
● Python Network Programming Cookbook
● Simple Client-Server Example
● Packet Sniffer Example
● File Transfer Example
● Unix Sockets Tutorial

More Related Content

What's hot

Python Functions
Python   FunctionsPython   Functions
Python Functions
Mohammed Sikander
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
Farooq Baloch
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket Programming
Vipin Yadav
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
ProfSonaliGholveDoif
 
Python GUI
Python GUIPython GUI
Python GUI
LusciousLarryDas
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
Functions in python
Functions in pythonFunctions in python
Functions in python
colorsof
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
Vineeta Garg
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha V
 
Union in c language
Union  in c languageUnion  in c language
Union in c language
tanmaymodi4
 
Constructor and destructor
Constructor  and  destructor Constructor  and  destructor
Constructor and destructor
Shubham Vishwambhar
 
programming with python ppt
programming with python pptprogramming with python ppt
programming with python ppt
Priyanka Pradhan
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
 
Python Presentation
Python PresentationPython Presentation
Python Presentation
Narendra Sisodiya
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
Tareq Hasan
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
Shuvongkor Barman
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
Vinod Kumar
 

What's hot (20)

Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
 
StringTokenizer in java
StringTokenizer in javaStringTokenizer in java
StringTokenizer in java
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket Programming
 
File handling in c++
File handling in c++File handling in c++
File handling in c++
 
Python GUI
Python GUIPython GUI
Python GUI
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Pointers in c++
Pointers in c++Pointers in c++
Pointers in c++
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Union in c language
Union  in c languageUnion  in c language
Union in c language
 
Constructor and destructor
Constructor  and  destructor Constructor  and  destructor
Constructor and destructor
 
programming with python ppt
programming with python pptprogramming with python ppt
programming with python ppt
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Python Presentation
Python PresentationPython Presentation
Python Presentation
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 

Viewers also liked

Network programming in python..
Network programming in python..Network programming in python..
Network programming in python..Bharath Kumar
 
Python - A Comprehensive Programming Language
Python - A Comprehensive Programming LanguagePython - A Comprehensive Programming Language
Python - A Comprehensive Programming Language
TsungWei Hu
 
파이썬+네트워크 20160210
파이썬+네트워크 20160210파이썬+네트워크 20160210
파이썬+네트워크 20160210
Yong Joon Moon
 
Introduction image processing
Introduction image processingIntroduction image processing
Introduction image processingAshish Kumar
 
online game over cryptography
online game over cryptographyonline game over cryptography
online game over cryptography
Ashish Kumar
 
02 psychovisual perception DIP
02 psychovisual perception DIP02 psychovisual perception DIP
02 psychovisual perception DIP
babak danyal
 
Python Programming - I. Introduction
Python Programming - I. IntroductionPython Programming - I. Introduction
Python Programming - I. Introduction
Ranel Padon
 
04 image enhancement in spatial domain DIP
04 image enhancement in spatial domain DIP04 image enhancement in spatial domain DIP
04 image enhancement in spatial domain DIP
babak danyal
 
07 frequency domain DIP
07 frequency domain DIP07 frequency domain DIP
07 frequency domain DIP
babak danyal
 
Image processing spatialfiltering
Image processing spatialfilteringImage processing spatialfiltering
Image processing spatialfilteringJohn Williams
 
01 introduction DIP
01 introduction DIP01 introduction DIP
01 introduction DIP
babak danyal
 
Digitized images and
Digitized images andDigitized images and
Digitized images andAshish Kumar
 
Switchable Map APIs with Drupal
Switchable Map APIs with DrupalSwitchable Map APIs with Drupal
Switchable Map APIs with Drupal
Ranel Padon
 
6 spatial filtering p2
6 spatial filtering p26 spatial filtering p2
6 spatial filtering p2Gichelle Amon
 
5 spatial filtering p1
5 spatial filtering p15 spatial filtering p1
5 spatial filtering p1Gichelle Amon
 
Mathematical operations in image processing
Mathematical operations in image processingMathematical operations in image processing
Mathematical operations in image processing
Asad Ali
 
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Ranel Padon
 

Viewers also liked (20)

Network programming in python..
Network programming in python..Network programming in python..
Network programming in python..
 
Python - A Comprehensive Programming Language
Python - A Comprehensive Programming LanguagePython - A Comprehensive Programming Language
Python - A Comprehensive Programming Language
 
Net prog
Net progNet prog
Net prog
 
Python session 8
Python session 8Python session 8
Python session 8
 
파이썬+네트워크 20160210
파이썬+네트워크 20160210파이썬+네트워크 20160210
파이썬+네트워크 20160210
 
Introduction image processing
Introduction image processingIntroduction image processing
Introduction image processing
 
online game over cryptography
online game over cryptographyonline game over cryptography
online game over cryptography
 
02 psychovisual perception DIP
02 psychovisual perception DIP02 psychovisual perception DIP
02 psychovisual perception DIP
 
Python Programming - I. Introduction
Python Programming - I. IntroductionPython Programming - I. Introduction
Python Programming - I. Introduction
 
04 image enhancement in spatial domain DIP
04 image enhancement in spatial domain DIP04 image enhancement in spatial domain DIP
04 image enhancement in spatial domain DIP
 
07 frequency domain DIP
07 frequency domain DIP07 frequency domain DIP
07 frequency domain DIP
 
Image processing spatialfiltering
Image processing spatialfilteringImage processing spatialfiltering
Image processing spatialfiltering
 
01 introduction DIP
01 introduction DIP01 introduction DIP
01 introduction DIP
 
applist
applistapplist
applist
 
Digitized images and
Digitized images andDigitized images and
Digitized images and
 
Switchable Map APIs with Drupal
Switchable Map APIs with DrupalSwitchable Map APIs with Drupal
Switchable Map APIs with Drupal
 
6 spatial filtering p2
6 spatial filtering p26 spatial filtering p2
6 spatial filtering p2
 
5 spatial filtering p1
5 spatial filtering p15 spatial filtering p1
5 spatial filtering p1
 
Mathematical operations in image processing
Mathematical operations in image processingMathematical operations in image processing
Mathematical operations in image processing
 
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
 

Similar to Network programming Using Python

Network programming using python
Network programming using pythonNetwork programming using python
Network programming using python
Ali Nezhad
 
Pemrograman Jaringan
Pemrograman JaringanPemrograman Jaringan
Pemrograman Jaringan
belajarkomputer
 
sockets_intro.ppt
sockets_intro.pptsockets_intro.ppt
sockets_intro.ppt
AnilGupta681764
 
Sockets intro
Sockets introSockets intro
Sockets intro
AviNash ChaVhan
 
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
senthilnathans25
 
Os 2
Os 2Os 2
Raspberry pi Part 23
Raspberry pi Part 23Raspberry pi Part 23
Raspberry pi Part 23
Techvilla
 
Sockets
Sockets Sockets
Sockets
Gopaiah Sanaka
 
python programming
python programmingpython programming
python programming
keerthikaA8
 
network programing lab file ,
network programing lab file ,network programing lab file ,
network programing lab file ,
AAlha PaiKra
 
A.java
A.javaA.java
EN-04 (1).pptx
EN-04 (1).pptxEN-04 (1).pptx
EN-04 (1).pptx
TienTran779192
 
Networking & Socket Programming In Java
Networking & Socket Programming In JavaNetworking & Socket Programming In Java
Networking & Socket Programming In Java
Ankur Agrawal
 
Java 1
Java 1Java 1
Lab manual cn-2012-13
Lab manual cn-2012-13Lab manual cn-2012-13
Lab manual cn-2012-13Sasi Kala
 
lab04.pdf
lab04.pdflab04.pdf
lab04.pdf
SaidiCalala
 

Similar to Network programming Using Python (20)

Network programming using python
Network programming using pythonNetwork programming using python
Network programming using python
 
Pemrograman Jaringan
Pemrograman JaringanPemrograman Jaringan
Pemrograman Jaringan
 
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
 
Os 2
Os 2Os 2
Os 2
 
Python networking
Python networkingPython networking
Python networking
 
Raspberry pi Part 23
Raspberry pi Part 23Raspberry pi Part 23
Raspberry pi Part 23
 
Sockets
Sockets Sockets
Sockets
 
python programming
python programmingpython programming
python programming
 
10 Networking
10 Networking10 Networking
10 Networking
 
network programing lab file ,
network programing lab file ,network programing lab file ,
network programing lab file ,
 
A.java
A.javaA.java
A.java
 
Basic socket programming
Basic socket programmingBasic socket programming
Basic socket programming
 
EN-04 (1).pptx
EN-04 (1).pptxEN-04 (1).pptx
EN-04 (1).pptx
 
Networking & Socket Programming In Java
Networking & Socket Programming In JavaNetworking & Socket Programming In Java
Networking & Socket Programming In Java
 
Java 1
Java 1Java 1
Java 1
 
Md13 networking
Md13 networkingMd13 networking
Md13 networking
 
Lab manual cn-2012-13
Lab manual cn-2012-13Lab manual cn-2012-13
Lab manual cn-2012-13
 
lab04.pdf
lab04.pdflab04.pdf
lab04.pdf
 

Recently uploaded

Richard's aventures in two entangled wonderlands
Richard's aventures in two entangled wonderlandsRichard's aventures in two entangled wonderlands
Richard's aventures in two entangled wonderlands
Richard Gill
 
Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...
Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...
Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...
Sérgio Sacani
 
3D Hybrid PIC simulation of the plasma expansion (ISSS-14)
3D Hybrid PIC simulation of the plasma expansion (ISSS-14)3D Hybrid PIC simulation of the plasma expansion (ISSS-14)
3D Hybrid PIC simulation of the plasma expansion (ISSS-14)
David Osipyan
 
Deep Software Variability and Frictionless Reproducibility
Deep Software Variability and Frictionless ReproducibilityDeep Software Variability and Frictionless Reproducibility
Deep Software Variability and Frictionless Reproducibility
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
20240520 Planning a Circuit Simulator in JavaScript.pptx
20240520 Planning a Circuit Simulator in JavaScript.pptx20240520 Planning a Circuit Simulator in JavaScript.pptx
20240520 Planning a Circuit Simulator in JavaScript.pptx
Sharon Liu
 
Travis Hills' Endeavors in Minnesota: Fostering Environmental and Economic Pr...
Travis Hills' Endeavors in Minnesota: Fostering Environmental and Economic Pr...Travis Hills' Endeavors in Minnesota: Fostering Environmental and Economic Pr...
Travis Hills' Endeavors in Minnesota: Fostering Environmental and Economic Pr...
Travis Hills MN
 
Introduction to Mean Field Theory(MFT).pptx
Introduction to Mean Field Theory(MFT).pptxIntroduction to Mean Field Theory(MFT).pptx
Introduction to Mean Field Theory(MFT).pptx
zeex60
 
Chapter 12 - climate change and the energy crisis
Chapter 12 - climate change and the energy crisisChapter 12 - climate change and the energy crisis
Chapter 12 - climate change and the energy crisis
tonzsalvador2222
 
nodule formation by alisha dewangan.pptx
nodule formation by alisha dewangan.pptxnodule formation by alisha dewangan.pptx
nodule formation by alisha dewangan.pptx
alishadewangan1
 
Comparing Evolved Extractive Text Summary Scores of Bidirectional Encoder Rep...
Comparing Evolved Extractive Text Summary Scores of Bidirectional Encoder Rep...Comparing Evolved Extractive Text Summary Scores of Bidirectional Encoder Rep...
Comparing Evolved Extractive Text Summary Scores of Bidirectional Encoder Rep...
University of Maribor
 
ANAMOLOUS SECONDARY GROWTH IN DICOT ROOTS.pptx
ANAMOLOUS SECONDARY GROWTH IN DICOT ROOTS.pptxANAMOLOUS SECONDARY GROWTH IN DICOT ROOTS.pptx
ANAMOLOUS SECONDARY GROWTH IN DICOT ROOTS.pptx
RASHMI M G
 
Toxic effects of heavy metals : Lead and Arsenic
Toxic effects of heavy metals : Lead and ArsenicToxic effects of heavy metals : Lead and Arsenic
Toxic effects of heavy metals : Lead and Arsenic
sanjana502982
 
Orion Air Quality Monitoring Systems - CWS
Orion Air Quality Monitoring Systems - CWSOrion Air Quality Monitoring Systems - CWS
Orion Air Quality Monitoring Systems - CWS
Columbia Weather Systems
 
Leaf Initiation, Growth and Differentiation.pdf
Leaf Initiation, Growth and Differentiation.pdfLeaf Initiation, Growth and Differentiation.pdf
Leaf Initiation, Growth and Differentiation.pdf
RenuJangid3
 
SAR of Medicinal Chemistry 1st by dk.pdf
SAR of Medicinal Chemistry 1st by dk.pdfSAR of Medicinal Chemistry 1st by dk.pdf
SAR of Medicinal Chemistry 1st by dk.pdf
KrushnaDarade1
 
Nutraceutical market, scope and growth: Herbal drug technology
Nutraceutical market, scope and growth: Herbal drug technologyNutraceutical market, scope and growth: Herbal drug technology
Nutraceutical market, scope and growth: Herbal drug technology
Lokesh Patil
 
Phenomics assisted breeding in crop improvement
Phenomics assisted breeding in crop improvementPhenomics assisted breeding in crop improvement
Phenomics assisted breeding in crop improvement
IshaGoswami9
 
THEMATIC APPERCEPTION TEST(TAT) cognitive abilities, creativity, and critic...
THEMATIC  APPERCEPTION  TEST(TAT) cognitive abilities, creativity, and critic...THEMATIC  APPERCEPTION  TEST(TAT) cognitive abilities, creativity, and critic...
THEMATIC APPERCEPTION TEST(TAT) cognitive abilities, creativity, and critic...
Abdul Wali Khan University Mardan,kP,Pakistan
 
Lateral Ventricles.pdf very easy good diagrams comprehensive
Lateral Ventricles.pdf very easy good diagrams comprehensiveLateral Ventricles.pdf very easy good diagrams comprehensive
Lateral Ventricles.pdf very easy good diagrams comprehensive
silvermistyshot
 
Remote Sensing and Computational, Evolutionary, Supercomputing, and Intellige...
Remote Sensing and Computational, Evolutionary, Supercomputing, and Intellige...Remote Sensing and Computational, Evolutionary, Supercomputing, and Intellige...
Remote Sensing and Computational, Evolutionary, Supercomputing, and Intellige...
University of Maribor
 

Recently uploaded (20)

Richard's aventures in two entangled wonderlands
Richard's aventures in two entangled wonderlandsRichard's aventures in two entangled wonderlands
Richard's aventures in two entangled wonderlands
 
Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...
Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...
Observation of Io’s Resurfacing via Plume Deposition Using Ground-based Adapt...
 
3D Hybrid PIC simulation of the plasma expansion (ISSS-14)
3D Hybrid PIC simulation of the plasma expansion (ISSS-14)3D Hybrid PIC simulation of the plasma expansion (ISSS-14)
3D Hybrid PIC simulation of the plasma expansion (ISSS-14)
 
Deep Software Variability and Frictionless Reproducibility
Deep Software Variability and Frictionless ReproducibilityDeep Software Variability and Frictionless Reproducibility
Deep Software Variability and Frictionless Reproducibility
 
20240520 Planning a Circuit Simulator in JavaScript.pptx
20240520 Planning a Circuit Simulator in JavaScript.pptx20240520 Planning a Circuit Simulator in JavaScript.pptx
20240520 Planning a Circuit Simulator in JavaScript.pptx
 
Travis Hills' Endeavors in Minnesota: Fostering Environmental and Economic Pr...
Travis Hills' Endeavors in Minnesota: Fostering Environmental and Economic Pr...Travis Hills' Endeavors in Minnesota: Fostering Environmental and Economic Pr...
Travis Hills' Endeavors in Minnesota: Fostering Environmental and Economic Pr...
 
Introduction to Mean Field Theory(MFT).pptx
Introduction to Mean Field Theory(MFT).pptxIntroduction to Mean Field Theory(MFT).pptx
Introduction to Mean Field Theory(MFT).pptx
 
Chapter 12 - climate change and the energy crisis
Chapter 12 - climate change and the energy crisisChapter 12 - climate change and the energy crisis
Chapter 12 - climate change and the energy crisis
 
nodule formation by alisha dewangan.pptx
nodule formation by alisha dewangan.pptxnodule formation by alisha dewangan.pptx
nodule formation by alisha dewangan.pptx
 
Comparing Evolved Extractive Text Summary Scores of Bidirectional Encoder Rep...
Comparing Evolved Extractive Text Summary Scores of Bidirectional Encoder Rep...Comparing Evolved Extractive Text Summary Scores of Bidirectional Encoder Rep...
Comparing Evolved Extractive Text Summary Scores of Bidirectional Encoder Rep...
 
ANAMOLOUS SECONDARY GROWTH IN DICOT ROOTS.pptx
ANAMOLOUS SECONDARY GROWTH IN DICOT ROOTS.pptxANAMOLOUS SECONDARY GROWTH IN DICOT ROOTS.pptx
ANAMOLOUS SECONDARY GROWTH IN DICOT ROOTS.pptx
 
Toxic effects of heavy metals : Lead and Arsenic
Toxic effects of heavy metals : Lead and ArsenicToxic effects of heavy metals : Lead and Arsenic
Toxic effects of heavy metals : Lead and Arsenic
 
Orion Air Quality Monitoring Systems - CWS
Orion Air Quality Monitoring Systems - CWSOrion Air Quality Monitoring Systems - CWS
Orion Air Quality Monitoring Systems - CWS
 
Leaf Initiation, Growth and Differentiation.pdf
Leaf Initiation, Growth and Differentiation.pdfLeaf Initiation, Growth and Differentiation.pdf
Leaf Initiation, Growth and Differentiation.pdf
 
SAR of Medicinal Chemistry 1st by dk.pdf
SAR of Medicinal Chemistry 1st by dk.pdfSAR of Medicinal Chemistry 1st by dk.pdf
SAR of Medicinal Chemistry 1st by dk.pdf
 
Nutraceutical market, scope and growth: Herbal drug technology
Nutraceutical market, scope and growth: Herbal drug technologyNutraceutical market, scope and growth: Herbal drug technology
Nutraceutical market, scope and growth: Herbal drug technology
 
Phenomics assisted breeding in crop improvement
Phenomics assisted breeding in crop improvementPhenomics assisted breeding in crop improvement
Phenomics assisted breeding in crop improvement
 
THEMATIC APPERCEPTION TEST(TAT) cognitive abilities, creativity, and critic...
THEMATIC  APPERCEPTION  TEST(TAT) cognitive abilities, creativity, and critic...THEMATIC  APPERCEPTION  TEST(TAT) cognitive abilities, creativity, and critic...
THEMATIC APPERCEPTION TEST(TAT) cognitive abilities, creativity, and critic...
 
Lateral Ventricles.pdf very easy good diagrams comprehensive
Lateral Ventricles.pdf very easy good diagrams comprehensiveLateral Ventricles.pdf very easy good diagrams comprehensive
Lateral Ventricles.pdf very easy good diagrams comprehensive
 
Remote Sensing and Computational, Evolutionary, Supercomputing, and Intellige...
Remote Sensing and Computational, Evolutionary, Supercomputing, and Intellige...Remote Sensing and Computational, Evolutionary, Supercomputing, and Intellige...
Remote Sensing and Computational, Evolutionary, Supercomputing, and Intellige...
 

Network programming Using Python

  • 2. Contents ● Sockets ● Socket Types ● Python socket module ● Socket Object Methods ● Applications ○ Echo Server ○ Network Sniffer ○ File Transfer
  • 3. Sockets ● The endpoints of a network connection ● Each host has a unique IP address ● Each service runs on a specific port ● Each connection is maintained on both ends by a socket ● Sockets API allows us to send and receive data ● Programming Languages provide modules and classes to use this API
  • 4. Socket Types ● Stream Sockets (SOCK_STREAM): ○ Connection-oriented ○ Use TCP ● Datagram Sockets (SOCK_DGRAM): ○ Connectionless ○ Use UDP ● Other types: ○ E.g. Raw Sockets ● We will use stream sockets
  • 5. Python socket module ● socket.socket(family, type, proto) ○ Create new socket object ● socket.SOCK_STREAM (default) ● socket.SOCK_DGRAM ● socket.gethostname() ○ returns a string containing host name of the machine ● socket.gethostbyname(hostname) ○ Translates hostname to ip address ● socket.gethostbyaddr(ip_address) ○ Translates ip address to host name
  • 7. Socket Object Methods (Server) ● socket.bind(address) ○ e.g. socket.bind((host, port)) ● socket.listen(backlog) ○ backlog specifies wait queue size ○ e.g. socket.listen(5) ● socket.accept() ○ Blocks until a client makes a connection ○ Returns (conn, address) where conn is a new socket object usable to send and receive data ○ address is the address bound to the socket on the other end of the connection
  • 8. Socket Object Methods ● socket.connect(address) - used by client ○ e.g. socket.connect((host, port)) ● socket.send(bytes, flags) ○ e.g. socket.send(b‘Hello, World!’) ● socket.recv(bufsize, flags) ○ e.g. socket.recv(1024) ○ bufsize specify maximum amount of data in bytes to be received at once ● socket.close() ○ close connection
  • 9. Example 1: Echo Server # Echo server program import socket HOST = socket.gethostname() 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 True: data = conn.recv(1024) if not data: break conn.send(data) conn.close()
  • 10. Example 1: Echo Server # Echo client program import socket HOST = 'localhost' PORT = 50007 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.send(b'Hello, world') data = s.recv(1024) s.close() print('Received', repr(data))
  • 11. Example 2: Basic Network Sniffer #Packet sniffer in python #For Linux import socket #create an INET, raw socket s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_TCP) # receive a packet while True: print s.recvfrom(65565) Full Example with Packet Parsing
  • 12. Example 3: File Transfer # file_transfer_server.py import socket host = socket.gethostname() port = 6000 s = socket.socket() s.bind((host, port)) s.listen(5) print('Server listening..') ...
  • 13. Example 3: File Transfer # file_transfer_server.py ... while True: conn, addr = s.accept() print('New Connection from {}'.format(addr)) with open('test.txt', 'r') as f: while True: l = f.read(1024) if not l: break conn.send(l.encode()) print('Sent {}'.format(l)) print('Finished Sending.') conn.close() print('Connection closed')
  • 14. Example 3: File Transfer # file_transfer_client.py import socket # Import socket module s = socket.socket() # Create a socket object host = ‘localhost’ # Get local machine name port = 6000 # Reserve a port for your service. s.connect((host, port)) with open('received.txt', 'w') as f: print('Downloading file..') while True: data = s.recv(1024) if not data: break f.write(data.decode()) print('Received: {}n'.format(data.decode())) print('File downloaded successfully.') s.close() # Close the socket when done print('Connection closed')
  • 15. Code The previous examples and more can be found at: https://github.com/ksonbol/socket_examples
  • 16. Useful Resources ● Python socket module documentation ● Python Network Programming Cookbook ● Simple Client-Server Example ● Packet Sniffer Example ● File Transfer Example ● Unix Sockets Tutorial