SlideShare a Scribd company logo
http://www.tutorialspoint.com/python/python_networking .htm Copyright © tutorialspoint.com
PYTHON NETWORK PROGRAMMING
Pythonprovides two levels of access to network services. At a low level, youcanaccess the basic socket
support inthe underlying operating system, whichallows youto implement clients and servers for both
connection-oriented and connectionless protocols.
Pythonalso has libraries that provide higher-levelaccess to specific application-levelnetwork protocols, suchas
FTP, HTTP, and so on.
This tutorialgives youunderstanding onmost famous concept inNetworking - Socket Programming
What is Sockets?
Sockets are the endpoints of a bidirectionalcommunications channel. Sockets may communicate withina process,
betweenprocesses onthe same machine, or betweenprocesses ondifferent continents.
Sockets may be implemented over a number of different channeltypes: Unix domainsockets, TCP, UDP, and so
on. The socket library provides specific classes for handling the commontransports as wellas a generic
interface for handling the rest.
Sockets have their ownvocabulary:
Term Description
domain The family of protocols that willbe used as the transport mechanism. These values are
constants suchas AF_INET, PF_INET, PF_UNIX, PF_X25, and so on.
type The type of communications betweenthe two endpoints, typically SOCK_STREAM for
connection-oriented protocols and SOCK_DGRAM for connectionless protocols.
protocol Typically zero, this may be used to identify a variant of a protocolwithina domainand
type.
hostname The identifier of a network interface:
A string, whichcanbe a host name, a dotted-quad address, or anIPV6 address
incolon(and possibly dot) notation
A string "<broadcast>", whichspecifies anINADDR_BROADCAST address.
A zero-lengthstring, whichspecifies INADDR_ANY, or
AnInteger, interpreted as a binary address inhost byte order.
port Eachserver listens for clients calling onone or more ports. A port may be a Fixnum
port number, a string containing a port number, or the name of a service.
The socket Module:
To create a socket, youmust use the socket.socket() functionavailable insocket module, whichhas the general
syntax:
s = socket.socket (socket_family, socket_type, protocol=0)
Here is the descriptionof the parameters:
socket_family: This is either AF_UNIX or AF_INET, as explained earlier.
socket_type: This is either SOCK_STREAM or SOCK_DGRAM.
protocol: This is usually left out, defaulting to 0.
Once youhave socket object, thenyoucanuse required functions to create your client or server program.
Following is the list of functions required:
Server Socket Methods:
Method Description
s.bind() This method binds address (hostname, port number pair) to socket.
s.listen() This method sets up and start TCP listener.
s.accept() This passively accept TCP client connection, waiting untilconnectionarrives (blocking).
Client Socket Methods:
Method Description
s.connect() This method actively initiates TCP server connection.
General Socket Methods:
Method Description
s.recv() This method receives TCP message
s.send() This method transmits TCP message
s.recvfrom() This method receives UDP message
s.sendto() This method transmits UDP message
s.close() This method closes socket
socket.gethostname() Returns the hostname.
A Simple Server:
To write Internet servers, we use the socket functionavailable insocket module to create a socket object. A
socket object is thenused to callother functions to setup a socket server.
Now callbind(hostname, port functionto specify a port for your service onthe givenhost.
Next, callthe accept method of the returned object. This method waits untila client connects to the port you
specified, and thenreturns a connection object that represents the connectionto that client.
#!/usr/bin/python # This is server.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client.
print 'Got connection from', addr
c.send('Thank you for connecting')
c.close() # Close the connection
A Simple Client:
Now we willwrite a very simple client programwhichwillopena connectionto a givenport 12345 and givenhost.
This is very simple to create a socket client using Python's socket module function.
The socket.connect(hosname, port ) opens a TCP connectionto hostname onthe port. Once youhave a
socket open, youcanread fromit like any IO object. Whendone, remember to close it, as youwould close a file.
The following code is a very simple client that connects to a givenhost and port, reads any available data fromthe
socket, and thenexits:
#!/usr/bin/python # This is client.py file
import socket # Import socket module
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345 # Reserve a port for your service.
s.connect((host, port))
print s.recv(1024)
s.close # Close the socket when done
Now runthis server.py inbackground and thenrunabove client.py to see the result.
# Following would start a server in background.
$ python server.py &
# Once server is started run client as follows:
$ python client.py
This would produce following result:
Got connection from ('127.0.0.1', 48437)
Thank you for connecting
Python Internet modules
A list of some important modules whichcould be used inPythonNetwork/Internet programming.
Protocol Common function Port No Python module
HTTP Web pages 80 httplib, urllib, xmlrpclib
NNTP Usenet news 119 nntplib
FTP File transfers 20 ftplib, urllib
SMTP Sending email 25 smtplib
POP3 Fetching email 110 poplib
IMAP4 Fetching email 143 imaplib
Telnet Command lines 23 telnetlib
Gopher Document transfers 70 gopherlib, urllib
Please check allthe libraries mentioned above to work withFTP, SMTP, POP, and IMAP protocols.
Further Readings:
I have givenyoua quick start withSocket Programming. It's a big subject so its recommended to go throughthe
following link to find more detailon:
Unix Socket Programming.
PythonSocket Library and Modules.

More Related Content

What's hot (20)

PDF
Socket programming
NemiRathore
 
PPT
Socket programming-tutorial-sk
sureshkarthick37
 
PDF
Network Sockets
Peter R. Egli
 
PPT
Ppt of socket
Amandeep Kaur
 
PDF
Socket programming
Rajivarnan (Rajiv)
 
PDF
Java- Datagram Socket class & Datagram Packet class
Ruchi Maurya
 
PDF
Socket programming using java
UC San Diego
 
PPTX
Advance Java-Network Programming
ashok hirpara
 
PDF
Java sockets
Stephen Pradeep
 
PPT
Java Socket Programming
Vipin Yadav
 
PPTX
Network programming in java - PPT
kamal kotecha
 
DOC
socket programming
prashantzagade
 
PDF
Ipc
deepakittude
 
PPT
Socket System Calls
Avinash Varma Kalidindi
 
PPT
Networking & Socket Programming In Java
Ankur Agrawal
 
PPT
Socket programming
chandramouligunnemeda
 
PPTX
Socket programming
Anurag Tomar
 
PPTX
Java socket programming
Mohammed Abdalla Youssif
 
PPTX
Python Sockets
pythontic
 
PPT
Sockets
sivindia
 
Socket programming
NemiRathore
 
Socket programming-tutorial-sk
sureshkarthick37
 
Network Sockets
Peter R. Egli
 
Ppt of socket
Amandeep Kaur
 
Socket programming
Rajivarnan (Rajiv)
 
Java- Datagram Socket class & Datagram Packet class
Ruchi Maurya
 
Socket programming using java
UC San Diego
 
Advance Java-Network Programming
ashok hirpara
 
Java sockets
Stephen Pradeep
 
Java Socket Programming
Vipin Yadav
 
Network programming in java - PPT
kamal kotecha
 
socket programming
prashantzagade
 
Socket System Calls
Avinash Varma Kalidindi
 
Networking & Socket Programming In Java
Ankur Agrawal
 
Socket programming
chandramouligunnemeda
 
Socket programming
Anurag Tomar
 
Java socket programming
Mohammed Abdalla Youssif
 
Python Sockets
pythontic
 
Sockets
sivindia
 

Similar to Python networking (20)

PPTX
Network programming using python
Ali Nezhad
 
PPTX
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
Maulik Borsaniya
 
PDF
Network programming Using Python
Karim Sonbol
 
PPTX
python programming
keerthikaA8
 
PPTX
CLIENT SERVER COMMUNICATION.pptx
VandanaGaria
 
PPTX
Network Programming-Python-13-8-2023.pptx
ssuser23035c
 
PPTX
session6-Network Programming.pptx
SrinivasanG52
 
PDF
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
Mohammad Reza Kamalifard
 
PDF
Socket Programming In Python
didip
 
PDF
Of the variedtypes of IPC, sockets arout and awaythe foremostcommon..pdf
anuradhasilks
 
PPT
Net prog
Kunal Dawn
 
PPT
Socket Programming_theory.ppt
mdrobinhossain4
 
PPTX
Basics of Socket Programming using python
NalinadeviKadiresan1
 
PPT
CHAT SERVER
Sine19
 
PDF
Python lecture 11
Tanwir Zaman
 
PPTX
Socket programming in python
Vignesh Suresh
 
PPT
Chapter_2_part5.ppt in the department of computer science
zahrabashir8320
 
PPT
Sockets in unix
swtjerin4u
 
PDF
Tornado Web Server Internals
Praveen Gollakota
 
Network programming using python
Ali Nezhad
 
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
Maulik Borsaniya
 
Network programming Using Python
Karim Sonbol
 
python programming
keerthikaA8
 
CLIENT SERVER COMMUNICATION.pptx
VandanaGaria
 
Network Programming-Python-13-8-2023.pptx
ssuser23035c
 
session6-Network Programming.pptx
SrinivasanG52
 
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
Mohammad Reza Kamalifard
 
Socket Programming In Python
didip
 
Of the variedtypes of IPC, sockets arout and awaythe foremostcommon..pdf
anuradhasilks
 
Net prog
Kunal Dawn
 
Socket Programming_theory.ppt
mdrobinhossain4
 
Basics of Socket Programming using python
NalinadeviKadiresan1
 
CHAT SERVER
Sine19
 
Python lecture 11
Tanwir Zaman
 
Socket programming in python
Vignesh Suresh
 
Chapter_2_part5.ppt in the department of computer science
zahrabashir8320
 
Sockets in unix
swtjerin4u
 
Tornado Web Server Internals
Praveen Gollakota
 
Ad

More from Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai (20)

PDF
PWM Arduino Experiment for Engineering pra
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
PDF
Artificial Intelligence (AI) application in Agriculture Area
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
PDF
VLSI Design Book CMOS_Circuit_Design__Layout__and_Simulation
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
PDF
Question Bank: Network Management in Telecommunication
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
PDF
INTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdf
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
PDF
Network Management Principles and Practice - 2nd Edition (2010)_2.pdf
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
PDF
Mini Project fo BE Engineering students
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
PDF
Mini Project for Engineering Students BE or Btech Engineering students
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
PDF
VLSI Design_LAB MANUAL By Umakant Gohatre
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
PDF
cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
PDF
Image Compression, Introduction Data Compression/ Data compression, modelling...
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
PDF
Introduction Data Compression/ Data compression, modelling and coding,Image C...
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
PWM Arduino Experiment for Engineering pra
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Artificial Intelligence (AI) application in Agriculture Area
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
VLSI Design Book CMOS_Circuit_Design__Layout__and_Simulation
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Question Bank: Network Management in Telecommunication
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
INTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdf
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Network Management Principles and Practice - 2nd Edition (2010)_2.pdf
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Mini Project fo BE Engineering students
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Mini Project for Engineering Students BE or Btech Engineering students
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
VLSI Design_LAB MANUAL By Umakant Gohatre
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Image Compression, Introduction Data Compression/ Data compression, modelling...
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Introduction Data Compression/ Data compression, modelling and coding,Image C...
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Ad

Recently uploaded (20)

PPTX
Introduction to Design of Machine Elements
PradeepKumarS27
 
PPTX
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
PPTX
Green Building & Energy Conservation ppt
Sagar Sarangi
 
PPTX
Introduction to Neural Networks and Perceptron Learning Algorithm.pptx
Kayalvizhi A
 
PPTX
GitOps_Repo_Structure for begeinner(Scaffolindg)
DanialHabibi2
 
PPTX
MPMC_Module-2 xxxxxxxxxxxxxxxxxxxxx.pptx
ShivanshVaidya5
 
PPTX
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
PPTX
原版一样(Acadia毕业证书)加拿大阿卡迪亚大学毕业证办理方法
Taqyea
 
PPTX
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
PDF
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
PPT
PPT2_Metal formingMECHANICALENGINEEIRNG .ppt
Praveen Kumar
 
PDF
Book.pdf01_Intro.ppt algorithm for preperation stu used
archu26
 
PPTX
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
PDF
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
PDF
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
PDF
6th International Conference on Machine Learning Techniques and Data Science ...
ijistjournal
 
DOCX
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
PPTX
Element 7. CHEMICAL AND BIOLOGICAL AGENT.pptx
merrandomohandas
 
PPTX
MobileComputingMANET2023 MobileComputingMANET2023.pptx
masterfake98765
 
PPTX
Break Statement in Programming with 6 Real Examples
manojpoojary2004
 
Introduction to Design of Machine Elements
PradeepKumarS27
 
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
Green Building & Energy Conservation ppt
Sagar Sarangi
 
Introduction to Neural Networks and Perceptron Learning Algorithm.pptx
Kayalvizhi A
 
GitOps_Repo_Structure for begeinner(Scaffolindg)
DanialHabibi2
 
MPMC_Module-2 xxxxxxxxxxxxxxxxxxxxx.pptx
ShivanshVaidya5
 
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
原版一样(Acadia毕业证书)加拿大阿卡迪亚大学毕业证办理方法
Taqyea
 
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
Set Relation Function Practice session 24.05.2025.pdf
DrStephenStrange4
 
PPT2_Metal formingMECHANICALENGINEEIRNG .ppt
Praveen Kumar
 
Book.pdf01_Intro.ppt algorithm for preperation stu used
archu26
 
Lecture 1 Shell and Tube Heat exchanger-1.pptx
mailforillegalwork
 
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
6th International Conference on Machine Learning Techniques and Data Science ...
ijistjournal
 
CS-802 (A) BDH Lab manual IPS Academy Indore
thegodhimself05
 
Element 7. CHEMICAL AND BIOLOGICAL AGENT.pptx
merrandomohandas
 
MobileComputingMANET2023 MobileComputingMANET2023.pptx
masterfake98765
 
Break Statement in Programming with 6 Real Examples
manojpoojary2004
 

Python networking

  • 1. http://www.tutorialspoint.com/python/python_networking .htm Copyright © tutorialspoint.com PYTHON NETWORK PROGRAMMING Pythonprovides two levels of access to network services. At a low level, youcanaccess the basic socket support inthe underlying operating system, whichallows youto implement clients and servers for both connection-oriented and connectionless protocols. Pythonalso has libraries that provide higher-levelaccess to specific application-levelnetwork protocols, suchas FTP, HTTP, and so on. This tutorialgives youunderstanding onmost famous concept inNetworking - Socket Programming What is Sockets? Sockets are the endpoints of a bidirectionalcommunications channel. Sockets may communicate withina process, betweenprocesses onthe same machine, or betweenprocesses ondifferent continents. Sockets may be implemented over a number of different channeltypes: Unix domainsockets, TCP, UDP, and so on. The socket library provides specific classes for handling the commontransports as wellas a generic interface for handling the rest. Sockets have their ownvocabulary: Term Description domain The family of protocols that willbe used as the transport mechanism. These values are constants suchas AF_INET, PF_INET, PF_UNIX, PF_X25, and so on. type The type of communications betweenthe two endpoints, typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols. protocol Typically zero, this may be used to identify a variant of a protocolwithina domainand type. hostname The identifier of a network interface: A string, whichcanbe a host name, a dotted-quad address, or anIPV6 address incolon(and possibly dot) notation A string "<broadcast>", whichspecifies anINADDR_BROADCAST address. A zero-lengthstring, whichspecifies INADDR_ANY, or AnInteger, interpreted as a binary address inhost byte order. port Eachserver listens for clients calling onone or more ports. A port may be a Fixnum port number, a string containing a port number, or the name of a service. The socket Module: To create a socket, youmust use the socket.socket() functionavailable insocket module, whichhas the general syntax: s = socket.socket (socket_family, socket_type, protocol=0) Here is the descriptionof the parameters: socket_family: This is either AF_UNIX or AF_INET, as explained earlier. socket_type: This is either SOCK_STREAM or SOCK_DGRAM.
  • 2. protocol: This is usually left out, defaulting to 0. Once youhave socket object, thenyoucanuse required functions to create your client or server program. Following is the list of functions required: Server Socket Methods: Method Description s.bind() This method binds address (hostname, port number pair) to socket. s.listen() This method sets up and start TCP listener. s.accept() This passively accept TCP client connection, waiting untilconnectionarrives (blocking). Client Socket Methods: Method Description s.connect() This method actively initiates TCP server connection. General Socket Methods: Method Description s.recv() This method receives TCP message s.send() This method transmits TCP message s.recvfrom() This method receives UDP message s.sendto() This method transmits UDP message s.close() This method closes socket socket.gethostname() Returns the hostname. A Simple Server: To write Internet servers, we use the socket functionavailable insocket module to create a socket object. A socket object is thenused to callother functions to setup a socket server. Now callbind(hostname, port functionto specify a port for your service onthe givenhost. Next, callthe accept method of the returned object. This method waits untila client connects to the port you specified, and thenreturns a connection object that represents the connectionto that client. #!/usr/bin/python # This is server.py file import socket # Import socket module s = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name port = 12345 # Reserve a port for your service. s.bind((host, port)) # Bind to the port s.listen(5) # Now wait for client connection.
  • 3. while True: c, addr = s.accept() # Establish connection with client. print 'Got connection from', addr c.send('Thank you for connecting') c.close() # Close the connection A Simple Client: Now we willwrite a very simple client programwhichwillopena connectionto a givenport 12345 and givenhost. This is very simple to create a socket client using Python's socket module function. The socket.connect(hosname, port ) opens a TCP connectionto hostname onthe port. Once youhave a socket open, youcanread fromit like any IO object. Whendone, remember to close it, as youwould close a file. The following code is a very simple client that connects to a givenhost and port, reads any available data fromthe socket, and thenexits: #!/usr/bin/python # This is client.py file import socket # Import socket module s = socket.socket() # Create a socket object host = socket.gethostname() # Get local machine name port = 12345 # Reserve a port for your service. s.connect((host, port)) print s.recv(1024) s.close # Close the socket when done Now runthis server.py inbackground and thenrunabove client.py to see the result. # Following would start a server in background. $ python server.py & # Once server is started run client as follows: $ python client.py This would produce following result: Got connection from ('127.0.0.1', 48437) Thank you for connecting Python Internet modules A list of some important modules whichcould be used inPythonNetwork/Internet programming. Protocol Common function Port No Python module HTTP Web pages 80 httplib, urllib, xmlrpclib NNTP Usenet news 119 nntplib FTP File transfers 20 ftplib, urllib SMTP Sending email 25 smtplib POP3 Fetching email 110 poplib IMAP4 Fetching email 143 imaplib Telnet Command lines 23 telnetlib Gopher Document transfers 70 gopherlib, urllib
  • 4. Please check allthe libraries mentioned above to work withFTP, SMTP, POP, and IMAP protocols. Further Readings: I have givenyoua quick start withSocket Programming. It's a big subject so its recommended to go throughthe following link to find more detailon: Unix Socket Programming. PythonSocket Library and Modules.