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

What's hot (20)

Socket Programming In Python
Socket Programming In PythonSocket Programming In Python
Socket Programming In Python
didip
 
Python GUI Programming
Python GUI ProgrammingPython GUI Programming
Python GUI Programming
RTS Tech
 
Shell programming
Shell programmingShell programming
Shell programming
Moayad Moawiah
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
Emertxe Information Technologies Pvt Ltd
 
Python Basics
Python BasicsPython Basics
Python Basics
tusharpanda88
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Abhilash Nair
 
Python Collections Tutorial | Edureka
Python Collections Tutorial | EdurekaPython Collections Tutorial | Edureka
Python Collections Tutorial | Edureka
Edureka!
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
Emertxe Information Technologies Pvt Ltd
 
Date and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaDate and Time Module in Python | Edureka
Date and Time Module in Python | Edureka
Edureka!
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
baabtra.com - No. 1 supplier of quality freshers
 
STRINGS IN PYTHON
STRINGS IN PYTHONSTRINGS IN PYTHON
STRINGS IN PYTHON
TanushTM1
 
Object oriented programming in python
Object oriented programming in pythonObject oriented programming in python
Object oriented programming in python
baabtra.com - No. 1 supplier of quality freshers
 
NUMPY
NUMPY NUMPY
NUMPY
Global Academy of Technology
 
Python ppt
Python pptPython ppt
Python ppt
Mohita Pandey
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
Hamid Ghorbani
 
Java Streams
Java StreamsJava Streams
Java Streams
M Vishnuvardhan Reddy
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
Binay Kumar Ray
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha V
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
 
Python Programming Essentials - M23 - datetime module
Python Programming Essentials - M23 - datetime modulePython Programming Essentials - M23 - datetime module
Python Programming Essentials - M23 - datetime module
P3 InfoTech Solutions Pvt. Ltd.
 

Viewers also liked (20)

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
 
Net prog
Net progNet prog
Net prog
Kunal Dawn
 
Python session 8
Python session 8Python session 8
Python session 8
Navaneethan Naveen
 
파이썬+네트워크 20160210
파이썬+네트워크 20160210파이썬+네트워크 20160210
파이썬+네트워크 20160210
Yong Joon Moon
 
Introduction image processing
Introduction image processingIntroduction image processing
Introduction image processing
Ashish 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 spatialfiltering
John Williams
 
01 introduction DIP
01 introduction DIP01 introduction DIP
01 introduction DIP
babak danyal
 
applist
applistapplist
applist
babak danyal
 
Digitized images and
Digitized images andDigitized images and
Digitized images and
Ashish 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 p2
Gichelle Amon
 
5 spatial filtering p1
5 spatial filtering p15 spatial filtering p1
5 spatial filtering p1
Gichelle 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
 
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 processing
Ashish 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 spatialfiltering
John Williams
 
01 introduction DIP
01 introduction DIP01 introduction DIP
01 introduction DIP
babak danyal
 
Digitized images and
Digitized images andDigitized images and
Digitized images and
Ashish 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 p2
Gichelle Amon
 
5 spatial filtering p1
5 spatial filtering p15 spatial filtering p1
5 spatial filtering p1
Gichelle 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
 
Ad

Similar to Network programming Using Python (20)

Network programming using python
Network programming using pythonNetwork programming using python
Network programming using python
Ali Nezhad
 
Python networking
Python networkingPython networking
Python networking
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
python programming
python programmingpython programming
python programming
keerthikaA8
 
session6-Network Programming.pptx
session6-Network Programming.pptxsession6-Network Programming.pptx
session6-Network Programming.pptx
SrinivasanG52
 
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYAPYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
Maulik Borsaniya
 
Python network programming
Python   network programmingPython   network programming
Python network programming
Learnbay Datascience
 
Socket programming
Socket programmingSocket programming
Socket programming
NemiRathore
 
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونیاسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
Mohammad Reza Kamalifard
 
Network Programming-Python-13-8-2023.pptx
Network Programming-Python-13-8-2023.pptxNetwork Programming-Python-13-8-2023.pptx
Network Programming-Python-13-8-2023.pptx
ssuser23035c
 
Socket programming-in-python
Socket programming-in-pythonSocket programming-in-python
Socket programming-in-python
Yuvaraja Ravi
 
Of the variedtypes of IPC, sockets arout and awaythe foremostcommon..pdf
Of the variedtypes of IPC, sockets arout and awaythe foremostcommon..pdfOf the variedtypes of IPC, sockets arout and awaythe foremostcommon..pdf
Of the variedtypes of IPC, sockets arout and awaythe foremostcommon..pdf
anuradhasilks
 
Socket programming in python
Socket programming in pythonSocket programming in python
Socket programming in python
Vignesh Suresh
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
Praveen Gollakota
 
اسلاید دوم جلسه یازدهم کلاس پایتون برای هکر های قانونی
اسلاید دوم جلسه یازدهم کلاس پایتون برای هکر های قانونیاسلاید دوم جلسه یازدهم کلاس پایتون برای هکر های قانونی
اسلاید دوم جلسه یازدهم کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
Os 2
Os 2Os 2
Os 2
university of Gujrat, pakistan
 
Networking in python by Rj
Networking in python by RjNetworking in python by Rj
Networking in python by Rj
Shree M.L.Kakadiya MCA mahila college, Amreli
 
Sockets in unix
Sockets in unixSockets in unix
Sockets in unix
swtjerin4u
 
CLIENT SERVER COMMUNICATION.pptx
CLIENT SERVER COMMUNICATION.pptxCLIENT SERVER COMMUNICATION.pptx
CLIENT SERVER COMMUNICATION.pptx
VandanaGaria
 
Python for Networking Powerful for Automation
Python for Networking Powerful for AutomationPython for Networking Powerful for Automation
Python for Networking Powerful for Automation
skpdbz
 
socketProgramming-TCP-and UDP-overview.pdf
socketProgramming-TCP-and UDP-overview.pdfsocketProgramming-TCP-and UDP-overview.pdf
socketProgramming-TCP-and UDP-overview.pdf
Shilpachaudhari10
 
Network programming using python
Network programming using pythonNetwork programming using python
Network programming using python
Ali Nezhad
 
python programming
python programmingpython programming
python programming
keerthikaA8
 
session6-Network Programming.pptx
session6-Network Programming.pptxsession6-Network Programming.pptx
session6-Network Programming.pptx
SrinivasanG52
 
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYAPYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
Maulik Borsaniya
 
Socket programming
Socket programmingSocket programming
Socket programming
NemiRathore
 
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونیاسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
Mohammad Reza Kamalifard
 
Network Programming-Python-13-8-2023.pptx
Network Programming-Python-13-8-2023.pptxNetwork Programming-Python-13-8-2023.pptx
Network Programming-Python-13-8-2023.pptx
ssuser23035c
 
Socket programming-in-python
Socket programming-in-pythonSocket programming-in-python
Socket programming-in-python
Yuvaraja Ravi
 
Of the variedtypes of IPC, sockets arout and awaythe foremostcommon..pdf
Of the variedtypes of IPC, sockets arout and awaythe foremostcommon..pdfOf the variedtypes of IPC, sockets arout and awaythe foremostcommon..pdf
Of the variedtypes of IPC, sockets arout and awaythe foremostcommon..pdf
anuradhasilks
 
Socket programming in python
Socket programming in pythonSocket programming in python
Socket programming in python
Vignesh Suresh
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
Praveen Gollakota
 
اسلاید دوم جلسه یازدهم کلاس پایتون برای هکر های قانونی
اسلاید دوم جلسه یازدهم کلاس پایتون برای هکر های قانونیاسلاید دوم جلسه یازدهم کلاس پایتون برای هکر های قانونی
اسلاید دوم جلسه یازدهم کلاس پایتون برای هکر های قانونی
Mohammad Reza Kamalifard
 
Sockets in unix
Sockets in unixSockets in unix
Sockets in unix
swtjerin4u
 
CLIENT SERVER COMMUNICATION.pptx
CLIENT SERVER COMMUNICATION.pptxCLIENT SERVER COMMUNICATION.pptx
CLIENT SERVER COMMUNICATION.pptx
VandanaGaria
 
Python for Networking Powerful for Automation
Python for Networking Powerful for AutomationPython for Networking Powerful for Automation
Python for Networking Powerful for Automation
skpdbz
 
socketProgramming-TCP-and UDP-overview.pdf
socketProgramming-TCP-and UDP-overview.pdfsocketProgramming-TCP-and UDP-overview.pdf
socketProgramming-TCP-and UDP-overview.pdf
Shilpachaudhari10
 
Ad

Recently uploaded (20)

Gene Expression & Regulation in Eukaryotes.pptx
Gene Expression & Regulation in Eukaryotes.pptxGene Expression & Regulation in Eukaryotes.pptx
Gene Expression & Regulation in Eukaryotes.pptx
Muhammad Hassan Asadi
 
chemistry-class-ix-reference-study-material (1).pdf
chemistry-class-ix-reference-study-material (1).pdfchemistry-class-ix-reference-study-material (1).pdf
chemistry-class-ix-reference-study-material (1).pdf
s99808177
 
BOT-245_Breeding_of_Field_and_Horticultural_Crops.pdf
BOT-245_Breeding_of_Field_and_Horticultural_Crops.pdfBOT-245_Breeding_of_Field_and_Horticultural_Crops.pdf
BOT-245_Breeding_of_Field_and_Horticultural_Crops.pdf
zap6635
 
Algebra A BASIC REVIEW INTERMEDICATE ALGEBRA
Algebra A BASIC REVIEW INTERMEDICATE ALGEBRAAlgebra A BASIC REVIEW INTERMEDICATE ALGEBRA
Algebra A BASIC REVIEW INTERMEDICATE ALGEBRA
ropamadoda
 
TRABAJO INGLÉSssssssssssssssssssss (2).pptx
TRABAJO INGLÉSssssssssssssssssssss (2).pptxTRABAJO INGLÉSssssssssssssssssssss (2).pptx
TRABAJO INGLÉSssssssssssssssssssss (2).pptx
alejandroreina25
 
National development you must learn it.pptx
National development you must learn it.pptxNational development you must learn it.pptx
National development you must learn it.pptx
mukherjeechetan56
 
Microbiome Engineering: Shaping a Sustainable Future.pptx
Microbiome Engineering: Shaping a Sustainable Future.pptxMicrobiome Engineering: Shaping a Sustainable Future.pptx
Microbiome Engineering: Shaping a Sustainable Future.pptx
akshjm123
 
CloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy Texts
CloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy TextsCloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy Texts
CloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy Texts
sehilyi
 
Driving sustainability: AI adoption framework for the fast fashion industry
Driving sustainability: AI adoption framework for the fast fashion industryDriving sustainability: AI adoption framework for the fast fashion industry
Driving sustainability: AI adoption framework for the fast fashion industry
Selcen Ozturkcan
 
HOW TO FACE THREATS FROM THE FORCES OF NATURE EXISTING ON PLANET EARTH.pdf
HOW TO FACE THREATS FROM THE FORCES OF NATURE EXISTING ON PLANET EARTH.pdfHOW TO FACE THREATS FROM THE FORCES OF NATURE EXISTING ON PLANET EARTH.pdf
HOW TO FACE THREATS FROM THE FORCES OF NATURE EXISTING ON PLANET EARTH.pdf
Faga1939
 
Grammar-Based 
Interactive Visualization of Genomics Data
Grammar-Based 
Interactive Visualization of Genomics DataGrammar-Based 
Interactive Visualization of Genomics Data
Grammar-Based 
Interactive Visualization of Genomics Data
sehilyi
 
Comparative Layouts Revisited: Design Space, Guidelines, and Future Directions
Comparative Layouts Revisited: Design Space, Guidelines, and Future DirectionsComparative Layouts Revisited: Design Space, Guidelines, and Future Directions
Comparative Layouts Revisited: Design Space, Guidelines, and Future Directions
sehilyi
 
Struktur DNA dan kromosom dalam genetika
Struktur DNA dan kromosom dalam genetikaStruktur DNA dan kromosom dalam genetika
Struktur DNA dan kromosom dalam genetika
WiwitProbowati2
 
Agriculture fruit production for crrot candy amala candy banana sudi stem borrer
Agriculture fruit production for crrot candy amala candy banana sudi stem borrerAgriculture fruit production for crrot candy amala candy banana sudi stem borrer
Agriculture fruit production for crrot candy amala candy banana sudi stem borrer
kanopatel8840
 
Pushkar camel fest at college campus placement 2
Pushkar camel fest at college campus placement 2Pushkar camel fest at college campus placement 2
Pushkar camel fest at college campus placement 2
nandanitiwari82528
 
esmo-academy-2024-pptx-template smyth final.pdf
esmo-academy-2024-pptx-template smyth final.pdfesmo-academy-2024-pptx-template smyth final.pdf
esmo-academy-2024-pptx-template smyth final.pdf
GuillermoGutirrez33
 
Kim Sandwich Biomes Project Science 10.pptx
Kim Sandwich Biomes Project Science 10.pptxKim Sandwich Biomes Project Science 10.pptx
Kim Sandwich Biomes Project Science 10.pptx
asantos691
 
instrument of surgery help for the practical
instrument of surgery help for the practicalinstrument of surgery help for the practical
instrument of surgery help for the practical
radialcarpoulnaris
 
Immunity and its Types.hububhubibkinunubunni
Immunity and its Types.hububhubibkinunubunniImmunity and its Types.hububhubibkinunubunni
Immunity and its Types.hububhubibkinunubunni
Manveer19
 
Treatment of TMDS.by Dr.Devraj Neupane(MDS Resedent)
Treatment of TMDS.by Dr.Devraj Neupane(MDS Resedent)Treatment of TMDS.by Dr.Devraj Neupane(MDS Resedent)
Treatment of TMDS.by Dr.Devraj Neupane(MDS Resedent)
Dr.Devraj Neupane
 
Gene Expression & Regulation in Eukaryotes.pptx
Gene Expression & Regulation in Eukaryotes.pptxGene Expression & Regulation in Eukaryotes.pptx
Gene Expression & Regulation in Eukaryotes.pptx
Muhammad Hassan Asadi
 
chemistry-class-ix-reference-study-material (1).pdf
chemistry-class-ix-reference-study-material (1).pdfchemistry-class-ix-reference-study-material (1).pdf
chemistry-class-ix-reference-study-material (1).pdf
s99808177
 
BOT-245_Breeding_of_Field_and_Horticultural_Crops.pdf
BOT-245_Breeding_of_Field_and_Horticultural_Crops.pdfBOT-245_Breeding_of_Field_and_Horticultural_Crops.pdf
BOT-245_Breeding_of_Field_and_Horticultural_Crops.pdf
zap6635
 
Algebra A BASIC REVIEW INTERMEDICATE ALGEBRA
Algebra A BASIC REVIEW INTERMEDICATE ALGEBRAAlgebra A BASIC REVIEW INTERMEDICATE ALGEBRA
Algebra A BASIC REVIEW INTERMEDICATE ALGEBRA
ropamadoda
 
TRABAJO INGLÉSssssssssssssssssssss (2).pptx
TRABAJO INGLÉSssssssssssssssssssss (2).pptxTRABAJO INGLÉSssssssssssssssssssss (2).pptx
TRABAJO INGLÉSssssssssssssssssssss (2).pptx
alejandroreina25
 
National development you must learn it.pptx
National development you must learn it.pptxNational development you must learn it.pptx
National development you must learn it.pptx
mukherjeechetan56
 
Microbiome Engineering: Shaping a Sustainable Future.pptx
Microbiome Engineering: Shaping a Sustainable Future.pptxMicrobiome Engineering: Shaping a Sustainable Future.pptx
Microbiome Engineering: Shaping a Sustainable Future.pptx
akshjm123
 
CloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy Texts
CloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy TextsCloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy Texts
CloakingNote: A Novel Desktop Interface for Subtle Writing Using Decoy Texts
sehilyi
 
Driving sustainability: AI adoption framework for the fast fashion industry
Driving sustainability: AI adoption framework for the fast fashion industryDriving sustainability: AI adoption framework for the fast fashion industry
Driving sustainability: AI adoption framework for the fast fashion industry
Selcen Ozturkcan
 
HOW TO FACE THREATS FROM THE FORCES OF NATURE EXISTING ON PLANET EARTH.pdf
HOW TO FACE THREATS FROM THE FORCES OF NATURE EXISTING ON PLANET EARTH.pdfHOW TO FACE THREATS FROM THE FORCES OF NATURE EXISTING ON PLANET EARTH.pdf
HOW TO FACE THREATS FROM THE FORCES OF NATURE EXISTING ON PLANET EARTH.pdf
Faga1939
 
Grammar-Based 
Interactive Visualization of Genomics Data
Grammar-Based 
Interactive Visualization of Genomics DataGrammar-Based 
Interactive Visualization of Genomics Data
Grammar-Based 
Interactive Visualization of Genomics Data
sehilyi
 
Comparative Layouts Revisited: Design Space, Guidelines, and Future Directions
Comparative Layouts Revisited: Design Space, Guidelines, and Future DirectionsComparative Layouts Revisited: Design Space, Guidelines, and Future Directions
Comparative Layouts Revisited: Design Space, Guidelines, and Future Directions
sehilyi
 
Struktur DNA dan kromosom dalam genetika
Struktur DNA dan kromosom dalam genetikaStruktur DNA dan kromosom dalam genetika
Struktur DNA dan kromosom dalam genetika
WiwitProbowati2
 
Agriculture fruit production for crrot candy amala candy banana sudi stem borrer
Agriculture fruit production for crrot candy amala candy banana sudi stem borrerAgriculture fruit production for crrot candy amala candy banana sudi stem borrer
Agriculture fruit production for crrot candy amala candy banana sudi stem borrer
kanopatel8840
 
Pushkar camel fest at college campus placement 2
Pushkar camel fest at college campus placement 2Pushkar camel fest at college campus placement 2
Pushkar camel fest at college campus placement 2
nandanitiwari82528
 
esmo-academy-2024-pptx-template smyth final.pdf
esmo-academy-2024-pptx-template smyth final.pdfesmo-academy-2024-pptx-template smyth final.pdf
esmo-academy-2024-pptx-template smyth final.pdf
GuillermoGutirrez33
 
Kim Sandwich Biomes Project Science 10.pptx
Kim Sandwich Biomes Project Science 10.pptxKim Sandwich Biomes Project Science 10.pptx
Kim Sandwich Biomes Project Science 10.pptx
asantos691
 
instrument of surgery help for the practical
instrument of surgery help for the practicalinstrument of surgery help for the practical
instrument of surgery help for the practical
radialcarpoulnaris
 
Immunity and its Types.hububhubibkinunubunni
Immunity and its Types.hububhubibkinunubunniImmunity and its Types.hububhubibkinunubunni
Immunity and its Types.hububhubibkinunubunni
Manveer19
 
Treatment of TMDS.by Dr.Devraj Neupane(MDS Resedent)
Treatment of TMDS.by Dr.Devraj Neupane(MDS Resedent)Treatment of TMDS.by Dr.Devraj Neupane(MDS Resedent)
Treatment of TMDS.by Dr.Devraj Neupane(MDS Resedent)
Dr.Devraj Neupane
 

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