×

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

Find key from value in dictionary python

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

5 minutes read.

CatPlot in Python

Python Seaborn Library Seaborn is a superb Python tool for displaying graphical statistics graphing. Seaborn provides different color schemes and attractive default styles to facilitate the creation of various statistics charts...

8 minutes read.

Conditional Statements in python

In this article, we will learn about conditional statements and how to apply conditional statements in Python. A decision-making statement is another name for a conditional statement. Decision-making is an important...

5 minutes read.

Self in Python

 “self" is neither a keyword nor has a special meaning in Python, but it has a place and a job to do in Object-oriented programming. When we create a class...

6 minutes read.

Multiprocessing in python

The word multiprocessing is used to compute the operation in which more than two processors run simultaneously with more than one central processor. The computer's performance increases gradually. Multiprocessing is...

6 minutes read.

How to Iterate through a Dictionary in Python

In this tutorial, we will learn how to interate throught the dictionary in the Python programming, using different approaches with example. Introduction to Dictionary in Python Dictionary is a special type of...

4 minutes read.

Python Tuple count() Method

Python Tuple count() Method The tuple.count() method in Python returns the number of times a specified value appears in the tuple. Syntax tuple.count(value) Parameter value- This parameter represents the element to search in the tuple Return This...

1 minute read.

Python Struct

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.

Python String isdigit() method

Python String isdigit() method The string.isdigit() method returns a boolean value true if all characters in the string are digits else for any other value it returns false. Syntax string.isdigit() Parameter NA Return This method returns a...

2 minutes read.

How to check if the dictionary is empty in Python?

What is a dictionary in Python? A directory is a collection of data but data is not ordered. Unlike other data types, it does not hold a single value as its...

3 minutes read.

Data Structures and Algorithms Using Python | Part 1

Data Structures: Data Structure is defined as a way to organize and store the data so that we can access the data and work more efficiently. Data structures also describe the...

18 minutes read.

Check Letter in a String Python

Checking a specific letter or a character in a given string or a string which is taken as an input from the user is possible in Python in broadly three...

3 minutes read.

Python Program to check whether a given number is Armstrong or not

Program to check whether a given number is Armstrong or not A number is said to be an Armstrong if the sum of each digit's cube of a given number equals...

1 minute read.

Python Sending Email

Python Sending Email Simple Mail Transfer Protocol (SMTP) is used to handle sending e-mail and routing e-mail between mail servers. When we send an email either form a web-application or from a local software...

3 minutes read.

Python program to find whether a given number is even or odd

Python program to find whether a given number is even or odd A number is said to be even if any number is completely divisible by 2, which means there is...

1 minute read.

Python Hash Table

An Introduction to Hashing A technique which used to identify a particular object uniquely from a set of similar objects is known as Hashing. Some real-life examples of hashing implementations include: A...

9 minutes read.

Exclusive OR in Python

In Python, the exclusive OR (XOR) operator is represented by the caret symbol (^). It compares each bit of the first operand to the corresponding bit of the second operand,...

3 minutes read.

Python SciPy Library

Introduction SciPy, a logical library for Python is an open-source, BSD-authorized library for arithmetic, science, and design. The SciPy library relies upon NumPy, which gives advantageous and quick N-dimensional exhibit control....

6 minutes read.

Python type() Function

Python type() Function The type() function in Python returns the type of an object. The return value is a type object and generally the same object as returned by object.__class__. Syntax class type(object)      ...

1 minute read.

Python Modules

Python Modules The Python module is a collection of definition and statements. It can contain functions, classes, and variables.  Combining the related code into a module makes the code easier to understand and use....

5 minutes read.