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:
How to capture all the HTTP packets using tcpdump
Next article icon

How to Capture udp Packets in Python

Last Updated : 31 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Capturing UDP (User Datagram Protocol) packets is a fundamental skill for network programmers and security enthusiasts. Python, being a versatile and powerful programming language, offers various libraries and tools to facilitate packet capture. In this article, we'll explore how to capture UDP packets using Python, specifically focusing on the popular library Scapy.

What are UDP Packets?

UDP, or User Datagram Protocol, is one of the core protocols of the Internet Protocol (IP) suite. It operates at the transport layer and provides a connectionless, lightweight, and fast communication method for data transfer between devices on a network. Unlike TCP (Transmission Control Protocol), which is connection-oriented and ensures reliable data delivery, UDP is connectionless and does not guarantee delivery or order of packets.

How to Capture UDP Packets in Python?

Below, are the step-by-step Implementation of How to Capture UDP Packets in Python.

Create a Virtual Environment

First, create the virtual environment using the below commands

python -m venv env 
.\env\Scripts\activate.ps1

File Structure

snii

Capture UDP Packets in Python

udp_response.py: In this example, This Python code creates a UDP server using the `socket` module. It specifies an IP address (127.0.0.1) and port (5005) to listen on, then creates a UDP socket. The server continuously listens for incoming UDP packets, printing details such as the sender's address and the received data in UTF-8 encoding. The `while True` loop ensures the server remains active and responsive to incoming UDP packets.

Python3
import socket  # Define the UDP IP address and port to listen on UDP_IP = "127.0.0.1" UDP_PORT = 5005  # Create a UDP socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((UDP_IP, UDP_PORT))  print(f"Listening for UDP packets on {UDP_IP}:{UDP_PORT}")  while True:     # Receive data from the socket     data, addr = sock.recvfrom(1024)     print(f"Received packet from {addr}: {data.decode('utf-8')}") 

packet.py: In this example, below code This Python script functions as a UDP client, sending the message "Hello, UDP!" to a specified target IP address and port (127.0.0.1:5005). It utilizes the `socket` module to create a UDP socket, sends the encoded message, and prints a confirmation. The `finally` block ensures proper socket closure.

Python3
import socket  UDP_IP = "127.0.0.1"  # Replace with the target IP address UDP_PORT = 5005       # Replace with the target port  message = "Hello, UDP!"  # send the message via socket  sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  try:     sock.sendto(message.encode(), (UDP_IP, UDP_PORT))     print(f"Sent UDP packet to {UDP_IP}:{UDP_PORT}: {message}") finally:     sock.close() 

Run the Server

use the below command for run the server.

python script_name.py

Output

udp_img
Sending and Receiving packets via socket

Video Demonstration

Advantages of UDP Packets in Python

  • Low Latency: UDP minimizes communication delays by eliminating connection setup overhead.
  • Simplicity: Lightweight and straightforward, UDP omits complex features for faster data transmission.
  • Broadcast/Multicast Support: UDP enables efficient one-to-many communication for applications like live streaming.
  • Connectionless Nature: No continuous connection maintenance simplifies data transfer in real-time scenarios.
  • Real-Time Application Suitability: Ideal for time-sensitive applications like online gaming or VoIP, prioritizing data flow over perfect delivery

Next Article
How to capture all the HTTP packets using tcpdump
author
abhilashgaurav003
Improve
Article Tags :
  • Python
  • Geeks Premier League
  • Geeks Premier League 2023
Practice Tags :
  • python

Similar Reads

  • How to capture all the HTTP packets using tcpdump
    Tcpdump is the command line tool that allows the user to capture and analyze network traffic by intercepting and displaying packets that are being created and received by the user's system. It allows users to capture and inspect network traffic in real-time as it passes through a network interface.
    9 min read
  • How to Get Open Port Banner in Python
    In this article, we will see how to Get Open Port Banner in Python. Here we will discuss  What is Port? Port is a terminology used on computer networks. You might know, that whenever you connect to the internet, your system or any device to which you are connecting is assigned an IP address.  So, wh
    4 min read
  • Viewing Packets You Have Captured in Wireshark
    Prerequisite: Wireshark – Packet Capturing and Analyzing After capturing some packets or after opening a previously saved captured file, we have to analyze and view the captured packets in detail. To view the packets that are displayed in the packet list pane, simply click on a packet that you want
    2 min read
  • Saving Captured Packets in Wireshark
    Prerequisite: Wireshark Packet Capturing and Analyzing In Wireshark, after capturing some traffic of a network we can save the capture file on our local device so that it can be analyzed thoroughly in the future. We can save captured packets by using the File → Save or File → Save As…​ menu items. T
    2 min read
  • How to Make a DNS Spoof attack using Scapy in Python?
    In this article, we are going to discuss how to make a DNS Spoof attack using Scapy in Python. Before starting we need to know few points: DNS Server: The Domain Name System provides a way to match human-readable domain names into IP addresses.  For example, when we search for google.com, the browse
    5 min read
  • How to Install Python-USPP on Linux?
    Python-USPP is a multi-platform Python library that allows communication between Python programs and USPP devices. This library is written in Python itself. It supports Windows, Linux, and MacOS. In this article, we will learn how to install this library in the Linux operating system. Python USPP in
    3 min read
  • How to control PC from anywhere using Python?
    Prerequisite - Socket programming in Python In this solution, we use the concept of Socket Programming for establishing communication between two computers. Socket Programming in Python Socket Programming is a way of connecting two systems on a network to communicate with each other. Sockets are the
    2 min read
  • How to Manipulate IP Addresses in Python using ipaddress Module?
    IP Address stands for internet protocol address. It's an identifying number that's related to a selected computer or network. When connected to the web, the IP address allows the computers to send and receive information. Python provides ipaddress module which provides the capabilities to create, ma
    5 min read
  • How to use pynput to make a Keylogger?
    Prerequisites: Python Programming LanguageThe package pynput.keyboard contains classes for controlling and monitoring the keyboard. pynput is the library of Python that can be used to capture keyboard inputs there the coolest use of this can lie in making keyloggers. The code for the keylogger is gi
    1 min read
  • Steps to Go To a Specific Packet in Wireshark
    Packet capturing is the process of recording all communication between a computer and other devices. The packets are then analyzed to determine what was said, how it was said when it was said, and where it came from. Packet capture can be used in many ways. One common use is for network forensics. N
    4 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