DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk3 min

Build a Simple UDP Client in Python That Handles Replies and Timeouts

A compact Python UDP client example that sends encoded bytes, receives a reply, and handles a timeout—plus practical notes on reliability, addressing and datagram size.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Create a UDP socket, send encoded bytes with sendto(), then use recvfrom() to wait for a reply. The example below adds a finite timeout so the client does not wait forever; a timeout means no response arrived in time, not necessarily that the server failed.

A minimal UDP client in Python

This IPv4 request-and-response example uses Python’s standard-library socket module. Change the host, port and message to match the server, which must be listening and must understand the message format.

As an Amazon Associate I earn from qualifying purchases.

import socket

HOST = "127.0.0.1"
PORT = 9999
MESSAGE = "hello"

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
    sock.settimeout(2.0)
    sock.sendto(MESSAGE.encode("utf-8"), (HOST, PORT))
    try:
        data, server_address = sock.recvfrom(4096)
    except TimeoutError:
        print("No response before timeout")
    else:
        print("Received", data.decode("utf-8", errors="replace"), "from", server_address)

The socket uses AF_INET for IPv4 and SOCK_DGRAM for UDP. The context manager closes it when the block ends. sendto() sends the encoded message to the destination tuple; recvfrom() returns the received bytes and the sender’s address. See the Python 3.14.8 socket documentation and its UDP server example for the complementary receive-and-reply pattern.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why the example encodes and decodes the message

Socket datagrams carry bytes, not Python text strings. The example encodes the outgoing text as UTF-8 and decodes the reply using the same encoding, replacing invalid byte sequences rather than failing during display. Both sides must agree on the encoding and on the application-level message format. If the protocol defines a binary payload, send and interpret those bytes according to that protocol instead.

What the timeout means

Socket operations block by default. settimeout(2.0) limits how long a blocking operation waits; if no data arrives within that interval, Python raises a timeout exception. The two-second interval here is an example choice, not a recommended value for every network or service.

A timeout is not proof that the server is down or that it did not process the request. UDP itself does not acknowledge delivery, and either the request or reply may be lost. If you add retries, the application protocol should account for duplicate requests, for example with request identifiers and defined duplicate handling. Catch other socket and address errors as appropriate: they are reported as OSError or its subclasses.

When to use other socket and response choices

IPv4 and IPv6

The example selects IPv4 with AF_INET. For IPv6, use AF_INET6 and the address tuple form required for that family. Hostname resolution can return different addresses depending on DNS and host configuration; use a numeric address when deterministic address selection matters.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Request-and-response or fire-and-forget

This example waits for a reply. A fire-and-forget client can omit recvfrom() if its application does not expect a response. Neither choice makes UDP reliable: RFC 768 describes the protocol as transaction-oriented and says delivery and duplicate protection are not guaranteed (RFC 768). Use TCP when the application needs a reliable, ordered byte stream, or build the required acknowledgement, ordering and duplicate-handling behavior into the application protocol.

Blocking, timeout and non-blocking operation

A finite timeout suits a small synchronous example. An event-driven program may instead use setblocking(False) and readiness polling. That changes how the program waits; it does not add delivery guarantees.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Datagram size and message boundaries

UDP preserves datagram boundaries, so each receive gets a message rather than an arbitrary slice of a continuous stream. The 4096 passed to recvfrom() is the receive buffer size in this example, not a general maximum safe UDP message size.

Large datagrams may require IP fragmentation, which can reduce efficiency and reliability. The appropriate size depends on the network path; avoid assuming that a datagram that works on one network will work everywhere. RFC 8085 discusses fragmentation and UDP usage considerations in more detail (RFC 8085). A zero-length UDP payload is valid, so do not treat an empty received payload as TCP-style end-of-stream.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Troubleshoot a client that receives no reply

  • Check the endpoint: Confirm the server is listening on the intended host and port, and that the client is using the correct address family.
  • Check the protocol: Verify that the server accepts the bytes and encoding you send, and that it is expected to reply to this message.
  • Check network policy: Firewalls, routing or other network conditions can prevent a request or response from reaching its destination.
  • Interpret the timeout narrowly: It means no data arrived before the client’s deadline; it cannot identify whether the request was lost, the response was lost, or the server did not respond.
  • Inspect the returned address: recvfrom() provides the sender address along with the bytes, which can help identify where a reply came from.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.