SlideShare ist ein Scribd-Unternehmen logo
1 von 16
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt? (20)

Socket programming in Java (PPTX)
Socket programming in Java (PPTX)Socket programming in Java (PPTX)
Socket programming in Java (PPTX)
 
Python programming : Files
Python programming : FilesPython programming : Files
Python programming : Files
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
Threads in python
Threads in pythonThreads in python
Threads in python
 
Php array
Php arrayPhp array
Php array
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket Programming
 
Socket programming using java
Socket programming using javaSocket programming using java
Socket programming using java
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Files in java
Files in javaFiles in java
Files in java
 
parameter passing in c#
parameter passing in c#parameter passing in c#
parameter passing in c#
 
Python programming : Control statements
Python programming : Control statementsPython programming : Control statements
Python programming : Control statements
 
Php database connectivity
Php database connectivityPhp database connectivity
Php database connectivity
 
Java - Sockets
Java - SocketsJava - Sockets
Java - Sockets
 
Tcp/ip server sockets
Tcp/ip server socketsTcp/ip server sockets
Tcp/ip server sockets
 
CS8651 Internet Programming - Basics of HTML, HTML5, CSS
CS8651   Internet Programming - Basics of HTML, HTML5, CSSCS8651   Internet Programming - Basics of HTML, HTML5, CSS
CS8651 Internet Programming - Basics of HTML, HTML5, CSS
 
Signal
SignalSignal
Signal
 
Php Presentation
Php PresentationPhp Presentation
Php Presentation
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Ado.Net Tutorial
Ado.Net TutorialAdo.Net Tutorial
Ado.Net Tutorial
 

Andere mochten auch

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 LanguageTsungWei Hu
 
파이썬+네트워크 20160210
파이썬+네트워크 20160210파이썬+네트워크 20160210
파이썬+네트워크 20160210Yong 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 cryptographyAshish Kumar
 
02 psychovisual perception DIP
02 psychovisual perception DIP02 psychovisual perception DIP
02 psychovisual perception DIPbabak danyal
 
Python Programming - I. Introduction
Python Programming - I. IntroductionPython Programming - I. Introduction
Python Programming - I. IntroductionRanel 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 DIPbabak danyal
 
07 frequency domain DIP
07 frequency domain DIP07 frequency domain DIP
07 frequency domain DIPbabak danyal
 
Image processing spatialfiltering
Image processing spatialfilteringImage processing spatialfiltering
Image processing spatialfilteringJohn Williams
 
01 introduction DIP
01 introduction DIP01 introduction DIP
01 introduction DIPbabak 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 DrupalRanel 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 processingAsad 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
 

Andere mochten auch (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...
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Atp synthase , Atp synthase complex 1 to 4.
Atp synthase , Atp synthase complex 1 to 4.Atp synthase , Atp synthase complex 1 to 4.
Atp synthase , Atp synthase complex 1 to 4.Silpa
 
module for grade 9 for distance learning
module for grade 9 for distance learningmodule for grade 9 for distance learning
module for grade 9 for distance learninglevieagacer
 
PSYCHOSOCIAL NEEDS. in nursing II sem pptx
PSYCHOSOCIAL NEEDS. in nursing II sem pptxPSYCHOSOCIAL NEEDS. in nursing II sem pptx
PSYCHOSOCIAL NEEDS. in nursing II sem pptxSuji236384
 
Bhiwandi Bhiwandi ❤CALL GIRL 7870993772 ❤CALL GIRLS ESCORT SERVICE In Bhiwan...
Bhiwandi Bhiwandi ❤CALL GIRL 7870993772 ❤CALL GIRLS  ESCORT SERVICE In Bhiwan...Bhiwandi Bhiwandi ❤CALL GIRL 7870993772 ❤CALL GIRLS  ESCORT SERVICE In Bhiwan...
Bhiwandi Bhiwandi ❤CALL GIRL 7870993772 ❤CALL GIRLS ESCORT SERVICE In Bhiwan...Monika Rani
 
Phenolics: types, biosynthesis and functions.
Phenolics: types, biosynthesis and functions.Phenolics: types, biosynthesis and functions.
Phenolics: types, biosynthesis and functions.Silpa
 
Digital Dentistry.Digital Dentistryvv.pptx
Digital Dentistry.Digital Dentistryvv.pptxDigital Dentistry.Digital Dentistryvv.pptx
Digital Dentistry.Digital Dentistryvv.pptxMohamedFarag457087
 
Asymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 b
Asymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 bAsymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 b
Asymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 bSérgio Sacani
 
Molecular markers- RFLP, RAPD, AFLP, SNP etc.
Molecular markers- RFLP, RAPD, AFLP, SNP etc.Molecular markers- RFLP, RAPD, AFLP, SNP etc.
Molecular markers- RFLP, RAPD, AFLP, SNP etc.Silpa
 
300003-World Science Day For Peace And Development.pptx
300003-World Science Day For Peace And Development.pptx300003-World Science Day For Peace And Development.pptx
300003-World Science Day For Peace And Development.pptxryanrooker
 
The Mariana Trench remarkable geological features on Earth.pptx
The Mariana Trench remarkable geological features on Earth.pptxThe Mariana Trench remarkable geological features on Earth.pptx
The Mariana Trench remarkable geological features on Earth.pptxseri bangash
 
Climate Change Impacts on Terrestrial and Aquatic Ecosystems.pptx
Climate Change Impacts on Terrestrial and Aquatic Ecosystems.pptxClimate Change Impacts on Terrestrial and Aquatic Ecosystems.pptx
Climate Change Impacts on Terrestrial and Aquatic Ecosystems.pptxDiariAli
 
Thyroid Physiology_Dr.E. Muralinath_ Associate Professor
Thyroid Physiology_Dr.E. Muralinath_ Associate ProfessorThyroid Physiology_Dr.E. Muralinath_ Associate Professor
Thyroid Physiology_Dr.E. Muralinath_ Associate Professormuralinath2
 
Chemistry 5th semester paper 1st Notes.pdf
Chemistry 5th semester paper 1st Notes.pdfChemistry 5th semester paper 1st Notes.pdf
Chemistry 5th semester paper 1st Notes.pdfSumit Kumar yadav
 
TransientOffsetin14CAftertheCarringtonEventRecordedbyPolarTreeRings
TransientOffsetin14CAftertheCarringtonEventRecordedbyPolarTreeRingsTransientOffsetin14CAftertheCarringtonEventRecordedbyPolarTreeRings
TransientOffsetin14CAftertheCarringtonEventRecordedbyPolarTreeRingsSérgio Sacani
 
Proteomics: types, protein profiling steps etc.
Proteomics: types, protein profiling steps etc.Proteomics: types, protein profiling steps etc.
Proteomics: types, protein profiling steps etc.Silpa
 
GBSN - Microbiology (Unit 3)Defense Mechanism of the body
GBSN - Microbiology (Unit 3)Defense Mechanism of the body GBSN - Microbiology (Unit 3)Defense Mechanism of the body
GBSN - Microbiology (Unit 3)Defense Mechanism of the body Areesha Ahmad
 
FAIRSpectra - Enabling the FAIRification of Spectroscopy and Spectrometry
FAIRSpectra - Enabling the FAIRification of Spectroscopy and SpectrometryFAIRSpectra - Enabling the FAIRification of Spectroscopy and Spectrometry
FAIRSpectra - Enabling the FAIRification of Spectroscopy and SpectrometryAlex Henderson
 
Reboulia: features, anatomy, morphology etc.
Reboulia: features, anatomy, morphology etc.Reboulia: features, anatomy, morphology etc.
Reboulia: features, anatomy, morphology etc.Silpa
 

Kürzlich hochgeladen (20)

Atp synthase , Atp synthase complex 1 to 4.
Atp synthase , Atp synthase complex 1 to 4.Atp synthase , Atp synthase complex 1 to 4.
Atp synthase , Atp synthase complex 1 to 4.
 
module for grade 9 for distance learning
module for grade 9 for distance learningmodule for grade 9 for distance learning
module for grade 9 for distance learning
 
PSYCHOSOCIAL NEEDS. in nursing II sem pptx
PSYCHOSOCIAL NEEDS. in nursing II sem pptxPSYCHOSOCIAL NEEDS. in nursing II sem pptx
PSYCHOSOCIAL NEEDS. in nursing II sem pptx
 
Bhiwandi Bhiwandi ❤CALL GIRL 7870993772 ❤CALL GIRLS ESCORT SERVICE In Bhiwan...
Bhiwandi Bhiwandi ❤CALL GIRL 7870993772 ❤CALL GIRLS  ESCORT SERVICE In Bhiwan...Bhiwandi Bhiwandi ❤CALL GIRL 7870993772 ❤CALL GIRLS  ESCORT SERVICE In Bhiwan...
Bhiwandi Bhiwandi ❤CALL GIRL 7870993772 ❤CALL GIRLS ESCORT SERVICE In Bhiwan...
 
Phenolics: types, biosynthesis and functions.
Phenolics: types, biosynthesis and functions.Phenolics: types, biosynthesis and functions.
Phenolics: types, biosynthesis and functions.
 
Digital Dentistry.Digital Dentistryvv.pptx
Digital Dentistry.Digital Dentistryvv.pptxDigital Dentistry.Digital Dentistryvv.pptx
Digital Dentistry.Digital Dentistryvv.pptx
 
Asymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 b
Asymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 bAsymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 b
Asymmetry in the atmosphere of the ultra-hot Jupiter WASP-76 b
 
Molecular markers- RFLP, RAPD, AFLP, SNP etc.
Molecular markers- RFLP, RAPD, AFLP, SNP etc.Molecular markers- RFLP, RAPD, AFLP, SNP etc.
Molecular markers- RFLP, RAPD, AFLP, SNP etc.
 
300003-World Science Day For Peace And Development.pptx
300003-World Science Day For Peace And Development.pptx300003-World Science Day For Peace And Development.pptx
300003-World Science Day For Peace And Development.pptx
 
The Mariana Trench remarkable geological features on Earth.pptx
The Mariana Trench remarkable geological features on Earth.pptxThe Mariana Trench remarkable geological features on Earth.pptx
The Mariana Trench remarkable geological features on Earth.pptx
 
Climate Change Impacts on Terrestrial and Aquatic Ecosystems.pptx
Climate Change Impacts on Terrestrial and Aquatic Ecosystems.pptxClimate Change Impacts on Terrestrial and Aquatic Ecosystems.pptx
Climate Change Impacts on Terrestrial and Aquatic Ecosystems.pptx
 
Thyroid Physiology_Dr.E. Muralinath_ Associate Professor
Thyroid Physiology_Dr.E. Muralinath_ Associate ProfessorThyroid Physiology_Dr.E. Muralinath_ Associate Professor
Thyroid Physiology_Dr.E. Muralinath_ Associate Professor
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Clean In Place(CIP).pptx .
Clean In Place(CIP).pptx                 .Clean In Place(CIP).pptx                 .
Clean In Place(CIP).pptx .
 
Chemistry 5th semester paper 1st Notes.pdf
Chemistry 5th semester paper 1st Notes.pdfChemistry 5th semester paper 1st Notes.pdf
Chemistry 5th semester paper 1st Notes.pdf
 
TransientOffsetin14CAftertheCarringtonEventRecordedbyPolarTreeRings
TransientOffsetin14CAftertheCarringtonEventRecordedbyPolarTreeRingsTransientOffsetin14CAftertheCarringtonEventRecordedbyPolarTreeRings
TransientOffsetin14CAftertheCarringtonEventRecordedbyPolarTreeRings
 
Proteomics: types, protein profiling steps etc.
Proteomics: types, protein profiling steps etc.Proteomics: types, protein profiling steps etc.
Proteomics: types, protein profiling steps etc.
 
GBSN - Microbiology (Unit 3)Defense Mechanism of the body
GBSN - Microbiology (Unit 3)Defense Mechanism of the body GBSN - Microbiology (Unit 3)Defense Mechanism of the body
GBSN - Microbiology (Unit 3)Defense Mechanism of the body
 
FAIRSpectra - Enabling the FAIRification of Spectroscopy and Spectrometry
FAIRSpectra - Enabling the FAIRification of Spectroscopy and SpectrometryFAIRSpectra - Enabling the FAIRification of Spectroscopy and Spectrometry
FAIRSpectra - Enabling the FAIRification of Spectroscopy and Spectrometry
 
Reboulia: features, anatomy, morphology etc.
Reboulia: features, anatomy, morphology etc.Reboulia: features, anatomy, morphology etc.
Reboulia: features, anatomy, morphology etc.
 

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