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

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Socket programming
Socket programmingSocket programming
Socket programming
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sk
 
Network Sockets
Network SocketsNetwork Sockets
Network Sockets
 
Ppt of socket
Ppt of socketPpt of socket
Ppt of socket
 
Socket programming
Socket programming Socket programming
Socket programming
 
Java- Datagram Socket class & Datagram Packet class
Java- Datagram Socket class  & Datagram Packet classJava- Datagram Socket class  & Datagram Packet class
Java- Datagram Socket class & Datagram Packet class
 
Socket programming using java
Socket programming using javaSocket programming using java
Socket programming using java
 
Advance Java-Network Programming
Advance Java-Network ProgrammingAdvance Java-Network Programming
Advance Java-Network Programming
 
Java sockets
Java socketsJava sockets
Java sockets
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket Programming
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
socket programming
socket programming socket programming
socket programming
 
Ipc
IpcIpc
Ipc
 
Socket System Calls
Socket System CallsSocket System Calls
Socket System Calls
 
Networking & Socket Programming In Java
Networking & Socket Programming In JavaNetworking & Socket Programming In Java
Networking & Socket Programming In Java
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Java socket programming
Java socket programmingJava socket programming
Java socket programming
 
Python Sockets
Python SocketsPython Sockets
Python Sockets
 
Sockets
SocketsSockets
Sockets
 

Ähnlich wie Python networking

Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagarNitish Nagar
 
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.pptxssuser23035c
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in JavaTushar B Kute
 
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونیاسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونیMohammad Reza Kamalifard
 
Java Networking
Java NetworkingJava Networking
Java NetworkingSunil OS
 
Raspberry pi Part 23
Raspberry pi Part 23Raspberry pi Part 23
Raspberry pi Part 23Techvilla
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server InternalsPraveen Gollakota
 
Mail Server Project Report
Mail Server Project ReportMail Server Project Report
Mail Server Project ReportKavita Sharma
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in JavaTushar B Kute
 
CODE FOR echo_client.c A simple echo client using TCP #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP  #inc.pdfCODE FOR echo_client.c A simple echo client using TCP  #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP #inc.pdfsecunderbadtirumalgi
 

Ähnlich wie Python networking (20)

Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
 
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
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
A.java
A.javaA.java
A.java
 
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونیاسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
 
Os 2
Os 2Os 2
Os 2
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Md13 networking
Md13 networkingMd13 networking
Md13 networking
 
28 networking
28  networking28  networking
28 networking
 
Raspberry pi Part 23
Raspberry pi Part 23Raspberry pi Part 23
Raspberry pi Part 23
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
 
Networking in Java
Networking in JavaNetworking in Java
Networking in Java
 
#1 (TCPvs. UDP)
#1 (TCPvs. UDP)#1 (TCPvs. UDP)
#1 (TCPvs. UDP)
 
Mail Server Project Report
Mail Server Project ReportMail Server Project Report
Mail Server Project Report
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
CODE FOR echo_client.c A simple echo client using TCP #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP  #inc.pdfCODE FOR echo_client.c A simple echo client using TCP  #inc.pdf
CODE FOR echo_client.c A simple echo client using TCP #inc.pdf
 
Tcp/ip server sockets
Tcp/ip server socketsTcp/ip server sockets
Tcp/ip server sockets
 
java networking
 java networking java networking
java networking
 
Client server project
Client server projectClient server project
Client server project
 

Mehr von Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai

Mehr von Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai (20)

Artificial Intelligence (AI) application in Agriculture Area
Artificial Intelligence (AI) application in Agriculture Area Artificial Intelligence (AI) application in Agriculture Area
Artificial Intelligence (AI) application in Agriculture Area
 
VLSI Design Book CMOS_Circuit_Design__Layout__and_Simulation
VLSI Design Book CMOS_Circuit_Design__Layout__and_SimulationVLSI Design Book CMOS_Circuit_Design__Layout__and_Simulation
VLSI Design Book CMOS_Circuit_Design__Layout__and_Simulation
 
Question Bank: Network Management in Telecommunication
Question Bank: Network Management in TelecommunicationQuestion Bank: Network Management in Telecommunication
Question Bank: Network Management in Telecommunication
 
INTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdf
INTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdfINTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdf
INTRODUCTION TO CYBER LAW The Concept of Cyberspace Cyber law Cyber crime.pdf
 
LRU_Replacement-Policy.pdf
LRU_Replacement-Policy.pdfLRU_Replacement-Policy.pdf
LRU_Replacement-Policy.pdf
 
Network Management Principles and Practice - 2nd Edition (2010)_2.pdf
Network Management Principles and Practice - 2nd Edition (2010)_2.pdfNetwork Management Principles and Practice - 2nd Edition (2010)_2.pdf
Network Management Principles and Practice - 2nd Edition (2010)_2.pdf
 
Euler Method Details
Euler Method Details Euler Method Details
Euler Method Details
 
Mini Project fo BE Engineering students
Mini Project fo BE Engineering  students  Mini Project fo BE Engineering  students
Mini Project fo BE Engineering students
 
Mini Project for Engineering Students BE or Btech Engineering students
Mini Project for Engineering Students BE or Btech Engineering students Mini Project for Engineering Students BE or Btech Engineering students
Mini Project for Engineering Students BE or Btech Engineering students
 
Ballistics Detsils
Ballistics Detsils Ballistics Detsils
Ballistics Detsils
 
VLSI Design_LAB MANUAL By Umakant Gohatre
VLSI Design_LAB MANUAL By Umakant GohatreVLSI Design_LAB MANUAL By Umakant Gohatre
VLSI Design_LAB MANUAL By Umakant Gohatre
 
Cryptography and Network Security
Cryptography and Network SecurityCryptography and Network Security
Cryptography and Network Security
 
cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre
cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre
cyber crime, Cyber Security, Introduction, Umakant Bhaskar Gohatre
 
Image Compression, Introduction Data Compression/ Data compression, modelling...
Image Compression, Introduction Data Compression/ Data compression, modelling...Image Compression, Introduction Data Compression/ Data compression, modelling...
Image Compression, Introduction Data Compression/ Data compression, modelling...
 
Introduction Data Compression/ Data compression, modelling and coding,Image C...
Introduction Data Compression/ Data compression, modelling and coding,Image C...Introduction Data Compression/ Data compression, modelling and coding,Image C...
Introduction Data Compression/ Data compression, modelling and coding,Image C...
 
Python overview
Python overviewPython overview
Python overview
 
Python numbers
Python numbersPython numbers
Python numbers
 
Python multithreading
Python multithreadingPython multithreading
Python multithreading
 
Python modules
Python modulesPython modules
Python modules
 
Python loops
Python loopsPython loops
Python loops
 

Kürzlich hochgeladen

Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...ranjana rawat
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...roncy bisnoi
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSSIVASHANKAR N
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 

Kürzlich hochgeladen (20)

Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLSMANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
MANUFACTURING PROCESS-II UNIT-5 NC MACHINE TOOLS
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 

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.