Python Networking Programming





Python provides two levels of access to network services. At a low level, you can access the basic socket support in the underlying operating system, which allows you to implement clients and servers for both connection-oriented and connectionless protocols.

Python also has libraries that provide higher-level access to specific application-level network protocols, such as FTP, HTTP, and so on.

This chapter gives you understanding on most famous concept in Networking - Socket Programming.

What is Sockets?

Sockets are the endpoints of a bidirectional communications channel. Sockets may communicate within a process, between processes on the same machine, or between processes on different continents.

Topics You May Be Interested In
Python - Ds Introduction Python - Smtp
Python - Binary Tree Python - Imap
Python - Request Status Codes Python - Proxy Server
Python - Http Authentication Python - Capitalize And Translate
Python - Network Interface Python - Text Classification

Sockets may be implemented over a number of different channel types: Unix domain sockets, TCP, UDP, and so on. The socket library provides specific classes for handling the common transports as well as a generic interface for handling the rest.

Sockets have their own vocabulary −

Sr.No. Term & Description
1

Domain

The family of protocols that is used as the transport mechanism. These values are constants such as AF_INET, PF_INET, PF_UNIX, PF_X25, and so on.

Topics You May Be Interested In
Python - Ds Home Python - Http Client
Python - Ds Introduction Python - Text Processing
Python - Internet Protocol Python - Word Replacement
Python - Http Data Download Python - Process Word Document
Python - Network Interface Python - Text Wrapping
2

type

The type of communications between the two endpoints, typically SOCK_STREAM for connection-oriented protocols and SOCK_DGRAM for connectionless protocols.

3

protocol

Typically zero, this may be used to identify a variant of a protocol within a domain and type.

Topics You May Be Interested In
Python Files I/o Python - String Immutability
Python - Queue Python - Text Processing State Machine
Python - Divide And Conquer Python - Bigrams
Python - Tree Traversal Algorithms Python - Text Summarization
Python - Text Processing Introduction Python Object Oriented
4

hostname

The identifier of a network interface −

5

port

Each server listens for clients calling on one or more ports. A port may be a Fixnum port number, a string containing a port number, or the name of a service.

Topics You May Be Interested In
Python Files I/o Python - Http Server
Python Mysql Database Access Python - Telnet
Python - Sets Python - Synonyms And Antonyms
Python - Stack Python Basic Operators
Python - Network Interface Python Functions

The socket Module

To create a socket, you must use the socket.socket() function available in socket module, which has the general syntax −

s = socket.socket (socket_family, socket_type, protocol=0)

Here is the description of the parameters −

Once you have socket object, then you can use required functions to create your client or server program. Following is the list of functions required −

Server Socket Methods

Sr.No. Method & Description
1

s.bind()

This method binds address (hostname, port number pair) to socket.

Topics You May Be Interested In
Python Overview Python - Rss Feed
Python Modules Python - Reformatting Paragraphs
Python - Recursion Python - Synonyms And Antonyms
Python - Algorithm Justification Python - Corpora Access
Python - Http Server Python Exceptions Handling
2

s.listen()

This method sets up and start TCP listener.

3

s.accept()

This passively accept TCP client connection, waiting until connection arrives (blocking).

Topics You May Be Interested In
Python - Lists Python - Proxy Server
Python - Tree Traversal Algorithms Python - Backward File Reading
Python - Http Data Download Python - Wordnet Interface
Python - Smtp Python Tutorial
Python - Ssh Python Modules

Client Socket Methods

Sr.No. Method & Description
1

s.connect()

This method actively initiates TCP server connection.

General Socket Methods

Sr.No. Method & Description
1

s.recv()

This method receives TCP message

Topics You May Be Interested In
Python - Tuples Python - Email Messages
Python - Stack Python - Ftp
Python - Binary Tree Python - Tokenization
Python - Search Tree Python - Process Pdf
Python - Network Programming Python Object Oriented
2

s.send()

This method transmits TCP message

3

s.recvfrom()

This method receives UDP message

Topics You May Be Interested In
Python Date And Time Python - Search And Match
Python Sending Email Using Smtp Python Decision Making
Python - Recursion Python Dictionary
Python - Http Data Download Python Object Oriented
Python - Word Replacement Python Cgi Programming
4

s.sendto()

This method transmits UDP message

5

s.close()

This method closes socket

Topics You May Be Interested In
Python Date And Time Python - Hash Table
Python Functions Python - Algorithm Design
Python Object Oriented Python - Backtracking
Python Mysql Database Access Python - Searching Algorithms
Python - Linked Lists Python - Remote Procedure Call
6

socket.gethostname()

Returns the hostname.

A Simple Server

To write Internet servers, we use the socket function available in socket module to create a socket object. A socket object is then used to call other functions to setup a socket server.

Now call bind(hostname, port) function to specify a port for your service on the given host.

Topics You May Be Interested In
Python Modules Python - Extract Url From Text
Python - Dictionary Python - Word Replacement
Python - Backtracking Python - Wordnet Interface
Python - Email Messages Python - Bigrams
Python - Web Servers Python Loops

Next, call the accept method of the returned object. This method waits until a client connects to the port you specified, and then returns a connection object that represents the connection to 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

Let us write a very simple client program which opens a connection to a given port 12345 and given host. This is very simple to create a socket client using Python's socket module function.

The socket.connect(hosname, port ) opens a TCP connection to hostname on the port. Once you have a socket open, you can read from it like any IO object. When done, remember to close it, as you would close a file.

The following code is a very simple client that connects to a given host and port, reads any available data from the socket, and then exits −

#!/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 run this server.py in background and then run above 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 in Python Network/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 all the libraries mentioned above to work with FTP, SMTP, POP, and IMAP protocols.

Further Readings

This was a quick start with Socket Programming. It is a vast subject. It is recommended to go through the following link to find more detail −



Frequently Asked Questions

+
Ans: Python MySQL Database Access - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python CGI Programming - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python Regular Expressions - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python Network Programming - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python Sending Email using SMTP - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python Multithreaded Programming - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python XML Processing - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python GUI Programming (Tkinter) - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python Extension Programming with C - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python Quick Guide - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python Tools/Utilities - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..
+
Ans: Python Useful Resources - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming. view more..




Rating - NAN/5
472 views

Advertisements