×

Python Network Programming

In network programming, python plays a very important role. Python provides full support for encoding and decoding data and network protocol in its standard library. Writing a network program in python is very simple compared to any other language like C++.

Python gives access to two levels of network services which are:

  • First, it provides low-level access. In low-level access, we can access and use the basic socket support of OS with the help of python libraries.
  • Second, it provides high-level access. In high-level access, we can access the application-level networks like HTTP, FTP, etc. using python libraries.

Now before moving forward with the main topic. Let’s get familiar with some smaller concepts like Socket.

What are Sockets?

Sockets can be defined as the end-point of a communication process. In any communication process, we have end-points between two similar processes, two different processes and within a common process. These end-points are called sockets. It uses different protocols for finding the connection type of communication between client and server. It can be implemented over different channels like TCP, UDP, etc.

Python provides socket methods which help in providing virtual sockets to the communicating processes.

Syntax

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

Let’s understand the vocabulary of Socket

  1. Domain: It is basically the family of protocols used for transportation.
  2. type: It represents the type of communication between two end-points.
  3. protocol: This is typically zero, but it can be used to identify the protocol used in the network.
  4. hostname: The identifier of the network. It can be any name given to the host.
  5. port: It is a specific number given to a port or a string value. It is used when the client calls for more than one port to reach the server.

Let’s understand some server methods

  • Server Socket Methods
    1. s.bind(): This method is used to bind the address to sockets.
    2. s.listen(): This method is used to set up and start a TCP listener.
    3. s.accept(): This method is used for accepting the TCP client connection.
  • Client Socket Methods
    1. s.connect(): This method is used to initiate server connections for TCP.
  • General Socket Methods
    1. s.recv():  This method is used to receive the TCP message.
    2. s.send(): This method is used to transmit the TCP message.
    3. s.recvfrom(): This method is used to receive the UDP message.
    4. s.sendto(): This method is used to transmit the UDP message.
    5. s.close(): This method is used for closing the sockets.
    6. socket.gethostname(): This method is used for returning the hostname.

A Simple Server

# Importing the socket module
import socket              


# Creating a socket object
sct = socket.socket()         
# Getting name for the local machine
host = socket.gethostname() 
# Reserving a port for the service.
port = 12445                
# Bind to the port
sct.bind((host, port))        


# waiting for the client connection.
sct.listen(7)                
while True:
   # Establishing the connection with the client.
   cs, adrs = sct.accept()     
   print 'Got connection from', adrs
   cs.send('Thank you for connecting to the server')
   cs.close()           

Explanation

In the above code, we made a socket object and reserved a port on our pc. After that, we have bounded our server to a specific port. In the above code, we have passed an empty string so that the server can listen to incoming connections from other computers as well. We have used 7 in the listen() method, which means that 7 connections are kept waiting until the server is busy, and after that, if an 8th socket tries to connect, the connection will be refused. In the end, we have used a while loop for accepting all incoming connections.

A Simple Client

This is client.py file which is used to set up the client-server.

# Importing the socket module
import socket               
# Creating a socket object
sct = socket.socket()         
# Getting a local machine name
host = socket.gethostname() 
# Reserving a port for services
port = 12445                
sct.connect((host, port))
print sct.recv(1024)
sct.close()                

Now, if we run this server.py in the background and then run client.py, we will get the connection.

# These commands will help in starting the server
$ python server.py & 


# After the server is started, we can run the client
$ python client.py

Output

Got connection from ('127.0.0.1', 48437)
Thank you for connecting

Related Topics

Commands in Python

In this tutorial, we will see some of the widely used python commands along with their syntaxes and examples. To make Python more user-friendly, developers have provided these commands to...

12 minutes read.

Comments in the Python Programming Language

In this tutorial, we will learn how to comment in multiple lines and paragraphs in the python programming language. Commenting a Paragraph in Python Most people think the importance of comments is...

2 minutes read.

Subprocess Module in Python

What is a Process? Every program will have its respective system state, i.e., the state in which it is running. A program that is in a running state or in a...

7 minutes read.

How to handle exceptions in python

Prerequisite: Exceptions and errors in Python What are Exceptions? Exceptions are run-time errors that unexpectedly occur and crash a program. When occurred, it alters the flow of the program. These errors are...

9 minutes read.

Python Support

Python Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

GET and POST requests using Python

‘GET’ and ‘POST’ are two request methods of Hypertext Transfer Protocol (HTTP). What is HTTP? HTTP stands for Hypertext Transfer Protocol. It is a collection of protocols which makes communication between client...

4 minutes read.

What is online python free IDE

An IDE is an acronym that stands for “Integrated development environment.” It is a software environment that has a software development package that consists of the code editor and builds...

4 minutes read.

Python property()

Python property() class The property() class in Python returns a property attribute. Syntax class property(fget=None, fset=None, fdel=None, doc=None) Parameter fget: This attribute is used for getting an attribute value. fset : This parameter sets an attribute value. fdel: It is a function for deleting...

1 minute read.

Python dir() function

Python dir() function The dir() function in Python returns all properties and methods of the specified object, without the values. Syntax dir([object]) Parameter object: This parameter represents the object one wants to see the valid attributes. Return This function...

2 minutes read.

Convert Float to Int in Python using Pandas

Introduction To play with huge amounts of data, in python we require a tool. The tool which is available in Python is pandas. A panda is an open-source library. It is...

4 minutes read.

Change Data Type in Python

Python is a dynamic language where it is not always required to consider every variable type. Python supports a wide range of data types, but There are mainly six data...

3 minutes read.

Python Indentation

Overview The spaces at the start of a code line are known as an indentation in Python programming. Indentation is only used for readability in other programming languages like C, C++,...

8 minutes read.

Periodogram in Python

Python:  Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Python Constructor

Introduction A constructor is defined as the special kind of function or method that is used for instance variables initialization during the creation of an object of a class. The constructor's task...

5 minutes read.

iobase Python

All I/O flow classes derive from this conceptual base class. Derived classes will have to execute several of the class's abstract data types. The loop method is supported by all members of...

4 minutes read.

Anaconda python 3 installation for windows 10

If you are a problem solver and like to solve programming questions, the anaconda distribution for python could be one of the best options to use and solve problems in...

3 minutes read.

Covariance in Python

Covariance is defined as the estimate of the difference of change between two variables or more variables. It defines the changes of two variables together. In Python, The covariance can...

2 minutes read.

String indices must be integers in Python

Lists, tuples, and strings are examples of iterable objects in Python whose items or characters can be retrieved by their index numbers. For instance, you might take the following action to...

3 minutes read.

Python Slice from Last Occurrence of K

Introduction We already know that in Python, cutting produces a sub-string out of a string. The variables start, stop, and step are used to set the slicing range. When dealing on...

3 minutes read.

Curdir Python

Python Programming Language Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

3 minutes read.