SlideShare a Scribd company logo
3
Most read
4
Most read
7
Most read
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

PDF
What is Socket Programming in Python | Edureka
Edureka!
 
PPTX
Unity 3d Basics
Chaudhry Talha Waseem
 
PPT
How technology impacts our lives ( finished)
Devon Saysell
 
PPTX
Nlp toolkits and_preprocessing_techniques
ankit_ppt
 
PDF
Socket programming using C
Ajit Nayak
 
PPTX
File management
Vishal Singh
 
PPTX
Cross Site Scripting Defense Presentation
Ikhade Maro Igbape
 
PPTX
Regular expressions in Python
Sujith Kumar
 
What is Socket Programming in Python | Edureka
Edureka!
 
Unity 3d Basics
Chaudhry Talha Waseem
 
How technology impacts our lives ( finished)
Devon Saysell
 
Nlp toolkits and_preprocessing_techniques
ankit_ppt
 
Socket programming using C
Ajit Nayak
 
File management
Vishal Singh
 
Cross Site Scripting Defense Presentation
Ikhade Maro Igbape
 
Regular expressions in Python
Sujith Kumar
 

What's hot (20)

PDF
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
PDF
Python network programming
Learnbay Datascience
 
PPTX
Networking in Java
Tushar B Kute
 
PPTX
Session tracking in servlets
vishal choudhary
 
PDF
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
PPTX
Static Data Members and Member Functions
MOHIT AGARWAL
 
PDF
Java conditional statements
Kuppusamy P
 
DOCX
Data Structures Using C Practical File
Rahul Chugh
 
PPTX
File handling in Python
Megha V
 
PPTX
Python OOPs
Binay Kumar Ray
 
PPS
Interface
kamal kotecha
 
ODP
Python Modules
Nitin Reddy Katkam
 
PPTX
PHP Presentation
JIGAR MAKHIJA
 
PPT
Synchronization.37
myrajendra
 
PPS
Java Exception handling
kamal kotecha
 
ODP
OOP java
xball977
 
PPTX
Arrays in Java
Abhilash Nair
 
PPT
Java Streams
M Vishnuvardhan Reddy
 
PPTX
Dynamic method dispatch
yugandhar vadlamudi
 
PDF
JavaScript - Chapter 11 - Events
WebStackAcademy
 
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
Python network programming
Learnbay Datascience
 
Networking in Java
Tushar B Kute
 
Session tracking in servlets
vishal choudhary
 
Python programming : Files
Emertxe Information Technologies Pvt Ltd
 
Static Data Members and Member Functions
MOHIT AGARWAL
 
Java conditional statements
Kuppusamy P
 
Data Structures Using C Practical File
Rahul Chugh
 
File handling in Python
Megha V
 
Python OOPs
Binay Kumar Ray
 
Interface
kamal kotecha
 
Python Modules
Nitin Reddy Katkam
 
PHP Presentation
JIGAR MAKHIJA
 
Synchronization.37
myrajendra
 
Java Exception handling
kamal kotecha
 
OOP java
xball977
 
Arrays in Java
Abhilash Nair
 
Java Streams
M Vishnuvardhan Reddy
 
Dynamic method dispatch
yugandhar vadlamudi
 
JavaScript - Chapter 11 - Events
WebStackAcademy
 
Ad

Viewers also liked (20)

PPT
Network programming in python..
Bharath Kumar
 
PDF
Python - A Comprehensive Programming Language
TsungWei Hu
 
PPT
Net prog
Kunal Dawn
 
PPT
Python session 8
Navaneethan Naveen
 
PPTX
파이썬+네트워크 20160210
Yong Joon Moon
 
PPT
Introduction image processing
Ashish Kumar
 
PPTX
online game over cryptography
Ashish Kumar
 
PPT
02 psychovisual perception DIP
babak danyal
 
PDF
Python Programming - I. Introduction
Ranel Padon
 
PPT
04 image enhancement in spatial domain DIP
babak danyal
 
PPT
07 frequency domain DIP
babak danyal
 
PPT
Image processing spatialfiltering
John Williams
 
PPT
01 introduction DIP
babak danyal
 
DOCX
applist
babak danyal
 
PPT
Digitized images and
Ashish Kumar
 
PDF
Switchable Map APIs with Drupal
Ranel Padon
 
PPT
6 spatial filtering p2
Gichelle Amon
 
PPT
5 spatial filtering p1
Gichelle Amon
 
PPTX
Mathematical operations in image processing
Asad Ali
 
PDF
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Ranel Padon
 
Network programming in python..
Bharath Kumar
 
Python - A Comprehensive Programming Language
TsungWei Hu
 
Net prog
Kunal Dawn
 
Python session 8
Navaneethan Naveen
 
파이썬+네트워크 20160210
Yong Joon Moon
 
Introduction image processing
Ashish Kumar
 
online game over cryptography
Ashish Kumar
 
02 psychovisual perception DIP
babak danyal
 
Python Programming - I. Introduction
Ranel Padon
 
04 image enhancement in spatial domain DIP
babak danyal
 
07 frequency domain DIP
babak danyal
 
Image processing spatialfiltering
John Williams
 
01 introduction DIP
babak danyal
 
applist
babak danyal
 
Digitized images and
Ashish Kumar
 
Switchable Map APIs with Drupal
Ranel Padon
 
6 spatial filtering p2
Gichelle Amon
 
5 spatial filtering p1
Gichelle Amon
 
Mathematical operations in image processing
Asad Ali
 
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Ranel Padon
 
Ad

Similar to Network programming Using Python (20)

PPTX
Network programming using python
Ali Nezhad
 
PPT
Pemrograman Jaringan
belajarkomputer
 
PPT
sockets_intro.ppt
AnilGupta681764
 
PPT
Sockets intro
AviNash ChaVhan
 
PPT
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
senthilnathans25
 
PPTX
Raspberry pi Part 23
Techvilla
 
PPT
Sockets
Gopaiah Sanaka
 
PPTX
python programming
keerthikaA8
 
PPTX
10 Networking
Deepak Hagadur Bheemaraju
 
PPTX
Lecture 1 Socket programming elementary tcp sockets.pptx
MonaSayed27
 
DOCX
network programing lab file ,
AAlha PaiKra
 
PPTX
A.java
JahnaviBhagat
 
PPT
Basic socket programming
Kristian Arjianto
 
PPTX
EN-04 (1).pptx
TienTran779192
 
PPT
Networking & Socket Programming In Java
Ankur Agrawal
 
PPTX
Java 1
VidyaVarshini3
 
PPT
Md13 networking
Rakesh Madugula
 
DOCX
Lab manual cn-2012-13
Sasi Kala
 
Network programming using python
Ali Nezhad
 
Pemrograman Jaringan
belajarkomputer
 
sockets_intro.ppt
AnilGupta681764
 
Sockets intro
AviNash ChaVhan
 
INTRODUCTION TO SOCKETS IN COMPUTER NETWORKS DEPT OF CSE.ppt
senthilnathans25
 
Raspberry pi Part 23
Techvilla
 
Sockets
Gopaiah Sanaka
 
python programming
keerthikaA8
 
Lecture 1 Socket programming elementary tcp sockets.pptx
MonaSayed27
 
network programing lab file ,
AAlha PaiKra
 
Basic socket programming
Kristian Arjianto
 
EN-04 (1).pptx
TienTran779192
 
Networking & Socket Programming In Java
Ankur Agrawal
 
Md13 networking
Rakesh Madugula
 
Lab manual cn-2012-13
Sasi Kala
 

Recently uploaded (20)

PPTX
Introduction to biochemistry.ppt-pdf_shotrs!
Vishnukanchi darade
 
PPTX
2019 Upper Respiratory Tract Infections.pptx
jackophyta10
 
PDF
Package-Aware Approach for Repository-Level Code Completion in Pharo
ESUG
 
PDF
Even Lighter Than Lightweiht: Augmenting Type Inference with Primitive Heuris...
ESUG
 
PPTX
Unit 4 - Astronomy and Astrophysics - Milky Way And External Galaxies
RDhivya6
 
PPTX
How to Add SBCGlobal.net Email to MacBook Air in Minutes
raymondjones7273
 
PPT
oscillatoria known as blue -green algae
Baher El-Nogoumy
 
PPTX
fghvqwhfugqaifbiqufbiquvbfuqvfuqyvfqvfouiqvfq
PERMISONJERWIN
 
PDF
JADESreveals a large population of low mass black holes at high redshift
Sérgio Sacani
 
PPTX
Discovery of Novel Antibiotics from Uncultured Microbes.pptx
SaakshiSharma26
 
PPTX
Seminar on ethics in biomedical research
poojabisht244
 
PDF
N-enhancement in GN-z11: First evidence for supermassive stars nucleosynthesi...
Sérgio Sacani
 
PDF
The Cosmic Symphony: How Photons Shape the Universe and Our Place Within It
kutatomoshi
 
PDF
Directing Generative AI for Pharo Documentation
ESUG
 
PPTX
Hydrocarbons Pollution. OIL pollutionpptx
AkCreation33
 
PPTX
biomolecules-class12th chapter board classespptx
SapnaTiwari58
 
PDF
10thstd imp basic notes of chemistry (1).pdf
sonakshisingh9472
 
PDF
Bacteria, Different sizes and Shapes of of bacteria
Vishal Sakhare
 
PDF
urticaria-1775-rahulkalal-250606145215-0ff37bc9.pdf
GajananPatil761074
 
PDF
Vera C. Rubin Observatory of interstellar Comet 3I ATLAS - July 21, 2025.pdf
SOCIEDAD JULIO GARAVITO
 
Introduction to biochemistry.ppt-pdf_shotrs!
Vishnukanchi darade
 
2019 Upper Respiratory Tract Infections.pptx
jackophyta10
 
Package-Aware Approach for Repository-Level Code Completion in Pharo
ESUG
 
Even Lighter Than Lightweiht: Augmenting Type Inference with Primitive Heuris...
ESUG
 
Unit 4 - Astronomy and Astrophysics - Milky Way And External Galaxies
RDhivya6
 
How to Add SBCGlobal.net Email to MacBook Air in Minutes
raymondjones7273
 
oscillatoria known as blue -green algae
Baher El-Nogoumy
 
fghvqwhfugqaifbiqufbiquvbfuqvfuqyvfqvfouiqvfq
PERMISONJERWIN
 
JADESreveals a large population of low mass black holes at high redshift
Sérgio Sacani
 
Discovery of Novel Antibiotics from Uncultured Microbes.pptx
SaakshiSharma26
 
Seminar on ethics in biomedical research
poojabisht244
 
N-enhancement in GN-z11: First evidence for supermassive stars nucleosynthesi...
Sérgio Sacani
 
The Cosmic Symphony: How Photons Shape the Universe and Our Place Within It
kutatomoshi
 
Directing Generative AI for Pharo Documentation
ESUG
 
Hydrocarbons Pollution. OIL pollutionpptx
AkCreation33
 
biomolecules-class12th chapter board classespptx
SapnaTiwari58
 
10thstd imp basic notes of chemistry (1).pdf
sonakshisingh9472
 
Bacteria, Different sizes and Shapes of of bacteria
Vishal Sakhare
 
urticaria-1775-rahulkalal-250606145215-0ff37bc9.pdf
GajananPatil761074
 
Vera C. Rubin Observatory of interstellar Comet 3I ATLAS - July 21, 2025.pdf
SOCIEDAD JULIO GARAVITO
 

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