Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Tips and Tricks for Competitive Programming
Next article icon

Python Network Programming

Last Updated : 06 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Python provides two levels of access to network programming. These are - 

  • Low-Level Access: At the low level, you can access the basic socket support of the operating system. You can implement client and server for both connection-oriented and connectionless protocols.
  • High-Level Access: At the high level allows to implement protocols like HTTP, FTP, etc.

In this article, we will discuss Network Socket Programming. But before getting started let's understand what are sockets.

What are Sockets?

Consider a bidirectional communication channel, the sockets are the endpoints of this communication channel. These sockets (endpoints) can communicate within a process, between processes on the same machine, or between processes on different machines. Sockets use different protocols for determining the connection type for port-to-port communication between clients and servers.

Sockets Vocabulary

Sockets have their own set of vocabulary, let's have a look at them - 

TermDescription
DomainThe set of protocols used for transport mechanisms like AF_INET, PF_INET, etc.
TypeType of communication between sockets
ProtocolIdentifies the type of protocol used within domain and type. Typically it is zero
PortThe server listens for clients calling on one or more ports. it can be a string containing a port number, a name of the service, or a Fixnum port
Hostname

Identifies a network interface. It can be a 

  • a string containing hostname, IPv6 address, or a double-quad address.
  • an integer
  • a zero-length string
  • a string "<broadcast>"

Socket Programming

Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while the other socket reaches out to the other to form a connection. The server forms the listener socket while the client reaches out to the server. They are the real backbones behind web browsing. In simpler terms, there is a server and a client. We can use the socket module for socket programming. For this, we have to include the socket module - 

import socket

to create a socket we have to use the socket.socket() method. 

Syntax:

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

Where, 

  • socket_family: Either AF_UNIX or AF_INET
  • socket_type: Either SOCK_STREAM or SOCK_DGRAM.
  • protocol: Usually left out, defaulting to 0.

Example:

Python
import socket   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print(s) 

Output:

<socket.socket fd=74, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('0.0.0.0', 0)>

The socket module provides various methods for both client and server-side programming. Let's see each method in detail.

Socket Server Methods

These methods are used on the server-side. Let's see each method in detail - 

Function NameDescription
s.bind()Binds address to the socket. The address contains the pair of hostname and the port number.
s.listen()Starts the TCP listener
s.accept()Passively accepts the TCP client connection and blocks until the connection arrives

Socket Client Methods

This method is used on the client side. Let's see this method in detail - 

Function NameDescription
s.connect()Actively starts the TCP server connection

Socket General Methods

These are the general methods of the socket module. Let's see each method in detail.

Function NameDescription
s.send()Sends the TCP message
s.sendto()Sends the UDP message
s.recv()Receives the TCP message
s.recvfrom()Receives the UDP message
s.close()Close the socket
socket.ghostname()Returns the host name

Simple Server Client Program

Server

A server has a bind() method which binds it to a specific IP and port so that it can listen to incoming requests on that IP and port. A server has a listen() method which puts the server into listening mode. This allows the server to listen to incoming connections. And last a server has an accept() and close() method. The accept method initiates a connection with the client and the close method closes the connection with the client. 

Example: Network Programming Server-Side

Python
# first of all import the socket library import socket  # next create a socket object s = socket.socket() print ("Socket successfully created")  # reserve a port on your computer in our # case it is 40674 but it can be anything port = 40674  # Next bind to the port # we have not typed any ip in the ip field # instead we have inputted an empty string # this makes the server listen to requests # coming from other computers on the network s.bind(('', port)) print ("socket binded to %s" %(port))  # put the socket into listening mode s.listen(5)     print ("socket is listening")  # a forever loop until we interrupt it or # an error occurs while True:      # Establish connection with client.     c, addr = s.accept()     print ('Got connection from', addr )      # send a thank you message to the client.     c.send(b'Thank you for connecting')      # Close the connection with the client     c.close() 

Explanation:

  • We made a socket object and reserved a port on our pc.
  • After that, we bound our server to the specified port. Passing an empty string means that the server can listen to incoming connections from other computers as well. If we would have passed 127.0.0.1 then it would have listened to only those calls made within the local computer.
  • After that, we put the server into listening mode. 5 here means that 5 connections are kept waiting if the server is busy and if a 6th socket tries to connect then the connection is refused.
  • At last, we make a while loop and start to accept all incoming connections and close those connections after a thank you message to all connected sockets.

Client

Now we need something with which a server can interact. We could tenet to the server like this just to know that our server is working. Type these commands in the terminal:

# start the server
python server.py

# keep the above terminal open
# now open another terminal and type:

telnet localhost 12345

Output :

network programing server side

In the telnet terminal you will get this:

network programming telnet server

This output shows that our server is working. Now for the client-side: 

Example: Network Programming Client Side

Python
# Import socket module import socket  # Create a socket object s = socket.socket()  # Define the port on which you want to connect port = 40674  # connect to the server on local computer s.connect(('127.0.0.1', port))  # receive data from the server print(s.recv(1024))  # close the connection s.close() 

Output:

python network programming server clientpython network programming client side

Explanation:

  • We connect to localhost on port 40674 (the port on which our server runs) and lastly, we receive data from the server and close the connection.
  • Now save this file as client.py and run it from the terminal after starting the server script.

Note: For more information on Socket Programming refer to our Socket Programming in Python Tutorial


Next Article
Python Tips and Tricks for Competitive Programming

N

nikhilaggarwal3
Improve
Article Tags :
  • Python
  • Python Programs
  • Python-Networking
Practice Tags :
  • python

Similar Reads

  • Python Event-Driven Programming
    Event-driven programming is a powerful paradigm used in Python for building responsive and scalable applications. In this model, the flow of the program is driven by events such as user actions, system notifications, or messages from other parts of the program. In this article, we will learn about e
    3 min read
  • Python Programs
    Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples. The below Python section contains a wide collection of Python programming examples. These Python c
    11 min read
  • A basic Python Programming Challenge
    This time we are not going to go into any theoretical stuff. Some months ago, I wrote a program in Python for my students so that they can practice basic BODMAS questions. The purpose was that the program should generate random set of questions (number of questions to be entered by the user) and the
    3 min read
  • Python List Creation Programs
    Python provides multiple ways to create lists based on different requirements, such as generating lists of numbers, creating nested lists, forming lists of tuples or dictionaries, and more. This article covers various ways to create lists efficiently, including: Generating lists of numbers, strings,
    2 min read
  • Python Tips and Tricks for Competitive Programming
    Python Programming language makes everything easier and straightforward. Effective use of its built-in libraries can save a lot of time and help with faster submissions while doing Competitive Programming. Below are few such useful tricks that every Pythonist should have at their fingertips: Convert
    4 min read
  • Print new line in Python
    In this article, we will explore various methods to print new lines in the code. Python provides us with a set of characters that performs a specific operation in the code. One such character is the new line character "\n" which inserts a new line. [GFGTABS] Python a = "Geeks\nfor\nGeeks"
    2 min read
  • Python Tutorial | Learn Python Programming Language
    Python Tutorial – Python is one of the most popular programming languages. It’s simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. Python is: A high-level language, used in web development, data science, automat
    10 min read
  • Output of Python Program | Set 1
    Predict the output of following python programs: Program 1: [GFGTABS] Python r = lambda q: q * 2 s = lambda q: q * 3 x = 2 x = r(x) x = s(x) x = r(x) print (x) [/GFGTABS]Output: 24Explanation : In the above program r and s are lambda functions or anonymous functions and q is the argument to both of
    3 min read
  • Output of Python program | Set 5
    Predict the output of the following programs: Program 1: [GFGTABS] Python def gfgFunction(): &quot;Geeksforgeeks is cool website for boosting up technical skills&quot; return 1 print (gfgFunction.__doc__[17:21]) [/GFGTABS]Output: coolExplanation: There is a docstring defined for this method,
    3 min read
  • Output of Python programs | Set 8
    Prerequisite - Lists in Python Predict the output of the following Python programs. Program 1 [GFGTABS] Python list = [1, 2, 3, None, (1, 2, 3, 4, 5), ['Geeks', 'for', 'Geeks']] print len(list) [/GFGTABS]Output: 6Explanation: The beauty of python list datatype is that within
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences