Python Network Programming

Python gives two dimensions of access to web administrations. :

  • Low-level web administrations bolster essential Sockets, which give a standard BSD Sockets API that gives access to all techniques for the fundamental working framework Socket interface.
  • The abnormal state organize administration module SocketServer, which gives a server-driven class that disentangles the improvement of web servers.

What is Socket?

Sockets, otherwise called "attachments", commonly send solicitations to the system or "get organize demands" through "attachments" to permit correspondence between procedures between hosts or on a solitary PC.

socket() function

In Python, we utilize the attachment() capacity to make an attachment with the accompanying syntax:

socket.socket([family[, type[,proto]]])


  • family: The attachment family can make AF_UNIX or AF_INET
  • type: The attachment type can be separated into SOCK_STREAM or SOCK_DGRAM
  • relying upon whether it is association arranged or non-associated.
  • protocol: Generally, the default is 0.

Socket object (worked in) method

function Description
Server Side Sockets
s.bind() Bind the location (have, port) to the attachment. Under AF_INET, the location is spoken to as a tuple (have, port).
s.listen() Start TCP tuning in. The overabundance indicates the greatest number of associations the working framework can suspend before dismissing the association. This esteem is no less than 1, and most applications are set to 5.
s.accept() Passively acknowledge TCP customer associations, (blocking) sitting tight for the association with arrive
Client Sockets
s.connect() Actively introduces the TCP server association. The arrangement of the general location is a tuple (hostname, port). On the off chance that the association isn't right, a socket.error blunder is returned.
s.connect_ex() The expanded rendition of the interface() work restores a mistake code when a blunder happens as opposed to tossing an exception
Public work attachment function
s.recv() Receive TCP information, the information is returned as a string, and bufsize determines the greatest measure of information to get. The banner gives extra data about the message and can typically be overlooked.
s.send() Send TCP information and send the information in string to the associated attachment. The arrival esteem is the quantity of bytes to send, which might be not exactly the byte size of string.
s.sendall() Completely send TCP information and send TCP information totally. Sends the information in the string to the associated attachment, however endeavors to send every one of the information before returning. Returns None effectively, and tosses a special case on the off chance that it comes up short.
s.recvfrom() Receive UDP information, like recv(), yet the arrival esteem is (information, address). Where information is the string containing the gotten information, and address is the attachment address of the transmitted information.
s.sendto() Send UDP information, send the information to the attachment, address is a tuple of the structure (ipaddr, port), indicate the remote location. The arrival esteem is the quantity of bytes sent.
s.close() Close the socket
s.getpeername() Returns the remote location of the association attachment. The arrival esteem is typically a tuple (ipaddr, port).
s.getsockname() restores the attachment's own location. Normally a tuple (ipaddr, port)
s.setsockopt(level,optname,value) Sets the estimation of the given attachment alternative.
s.getsockopt(level,optname[.buflen]) restores the estimation of the attachment alternative.
s.settimeout(timeout) Sets the timeout period for attachment activities. Timeout is a gliding point number like a flash. An estimation of None shows no timeout. By and large, the timeout ought to be set when the attachment is simply made, as they may be utilized for associated activities, (for example, connect())
s.gettimeout() Returns the estimation of the current timeout period like a flash. On the off chance that no timeout period is set, it returns None.
s.fileno() Returns the document descriptor of the attachment.
s.setblocking(flag) If the banner is 0, the attachment is set to non-blocking mode, generally the attachment is set to blocking mode (default). In non-blocking mode, if call to recv() does not discover any information, or if the send() call can't send information promptly, it will cause a socket.error special case.
s.makefile() Create a record related with the socket

Simple instance


We utilize the attachment module's socket capacity to make an attachment object. The attachment article can set an attachment administration by calling different capacities.

Now we can determine the port(port) of the administration by calling the bind(hostname, port) work.

Next, we consider the attachment article's accept strategy. This technique hangs tight for an association from the customer and returns a connection object showing that it is associated with the customer.

The complete code is as follows:

# -*- coding: UTF-8 -*-
# Filename:

import socket # import socket module

s = socket.socket() # create a socket object< Span class="pln">
Host = socket.gethostname() # Get local hostname 
Port = 12345 # Set Port
s.bind((host, port)) # binding port
s.listen(5) # Waiting for client connection
while True:
c, addr = s.accept() # Establish a client connection。
print 'Connection address:', addr
c.send('Welcome to the web tutorial!')
c.close() # Close the connection


Next we compose a straightforward customer occurrence to associate with the administration made above. The port number is 12345.


socket.connect(hosname, port ) strategy opens a TCP association with a specialist organization whose have is hostname is port. When associated, we can get the information from the server, recollecting that the association should be shut after the task is finished.

The complete code is as follows:

# -*- coding: UTF-8 -*-
# Filename:
import socket # Import socket Module

s = socket.socket() # create socket Object
host = socket.gethostname() # Object......
port = 12345 # Set the port number

s.connect((host, port))
print s.recv(1024)

Now we open two terminals, the first terminal executes the file:

$ python 

The second terminal executes the file:

$ python
Welcome to the web tutorial! 

At this point, we will open the first terminal and you will see the following information output:

Connected Address: ('', 62461)

Python Internet Module

Here are some imperative modules for Python arrange programming:

AgreementFeaturesPort Number Python module
HTTPWeb Access80httplib, urllib, xmlrpclib
NNTPRead and post news articles, regularly known as "posts"119nntplib
FTPFile Transfer20ftplib, urllib
SMTPSend Mail25smtplib
POP3Receive mail110poplib
IMAP4Get Mail143imaplib
Telnetcommand line23telnetlib
GopherInformation lookup70gopherlib, urllib

welookups is optimized for learning.© welookups 2018 -
All Right Reserved and you agree to have read and accepted our term and condition