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

PPTX
PDF
Python network programming
PDF
What is Socket Programming in Python | Edureka
PPT
Networking
PPT
Socket Programming
PDF
Socket programming-in-python
PPT
Application Layer and Socket Programming
PDF
Socket Programming
Python network programming
What is Socket Programming in Python | Edureka
Networking
Socket Programming
Socket programming-in-python
Application Layer and Socket Programming
Socket Programming

What's hot (20)

PDF
Socket programming
PPT
Socket programming-tutorial-sk
PDF
Network Sockets
PPT
Ppt of socket
PDF
Socket programming
PDF
Java- Datagram Socket class & Datagram Packet class
PDF
Socket programming using java
PPTX
Advance Java-Network Programming
PDF
Java sockets
PPT
Java Socket Programming
PPTX
Network programming in java - PPT
DOC
socket programming
PDF
PPT
Socket System Calls
PPT
Networking & Socket Programming In Java
PPT
Socket programming
PPTX
Socket programming
PPTX
Java socket programming
PPTX
Python Sockets
PPT
Sockets
Socket programming
Socket programming-tutorial-sk
Network Sockets
Ppt of socket
Socket programming
Java- Datagram Socket class & Datagram Packet class
Socket programming using java
Advance Java-Network Programming
Java sockets
Java Socket Programming
Network programming in java - PPT
socket programming
Socket System Calls
Networking & Socket Programming In Java
Socket programming
Socket programming
Java socket programming
Python Sockets
Sockets
Ad

Similar to Python networking (20)

PPT
Socket Programming - nitish nagar
PPT
Unit 8 Java
PPTX
Network Programming-Python-13-8-2023.pptx
PPT
Network programming in Java
PPTX
PDF
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
PPT
Java Networking
PPTX
Linux Systems Prograramming: Unix Domain, Internet Domain (TCP, UDP) Socket P...
PPT
Md13 networking
PDF
28 networking
PPTX
Chuong5_Networking_updated.Networking_updatedpptx
PPTX
Lecture 1 Socket programming elementary tcp sockets.pptx
PPTX
Raspberry pi Part 23
PDF
Tornado Web Server Internals
PPTX
Networking in Java
PPTX
#1 (TCPvs. UDP)
PPT
LECTURE-17(Socket Programming) Detailed.
DOCX
Mail Server Project Report
PPT
Network programming in Java
Socket Programming - nitish nagar
Unit 8 Java
Network Programming-Python-13-8-2023.pptx
Network programming in Java
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
Java Networking
Linux Systems Prograramming: Unix Domain, Internet Domain (TCP, UDP) Socket P...
Md13 networking
28 networking
Chuong5_Networking_updated.Networking_updatedpptx
Lecture 1 Socket programming elementary tcp sockets.pptx
Raspberry pi Part 23
Tornado Web Server Internals
Networking in Java
#1 (TCPvs. UDP)
LECTURE-17(Socket Programming) Detailed.
Mail Server Project Report
Network programming in Java
Ad

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

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

Recently uploaded (20)

PPTX
Lecture Notes Electrical Wiring System Components
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PPTX
Sustainable Sites - Green Building Construction
PDF
Digital Logic Computer Design lecture notes
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPTX
UNIT 4 Total Quality Management .pptx
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
additive manufacturing of ss316l using mig welding
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
Construction Project Organization Group 2.pptx
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PDF
Embodied AI: Ushering in the Next Era of Intelligent Systems
PPTX
web development for engineering and engineering
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
Lecture Notes Electrical Wiring System Components
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
Sustainable Sites - Green Building Construction
Digital Logic Computer Design lecture notes
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
UNIT 4 Total Quality Management .pptx
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
additive manufacturing of ss316l using mig welding
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Construction Project Organization Group 2.pptx
Automation-in-Manufacturing-Chapter-Introduction.pdf
Operating System & Kernel Study Guide-1 - converted.pdf
Embodied AI: Ushering in the Next Era of Intelligent Systems
web development for engineering and engineering
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Model Code of Practice - Construction Work - 21102022 .pdf
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx

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.