0
0
PythonHow-ToBeginner · 3 min read

How to Create UDP Socket in Python: Simple Guide

To create a UDP socket in Python, use socket.socket(socket.AF_INET, socket.SOCK_DGRAM). This creates a socket for sending and receiving UDP packets without establishing a connection.
📐

Syntax

The syntax to create a UDP socket in Python involves calling the socket.socket() function with two arguments:

  • socket.AF_INET: This specifies the address family for IPv4.
  • socket.SOCK_DGRAM: This specifies the socket type for UDP (datagram) communication.

This socket can then be used to send and receive UDP packets.

python
import socket

udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
💻

Example

This example shows how to create a UDP socket, send a message to a server, and receive a response.

python
import socket

# Create UDP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# Server address and port
server_address = ('localhost', 12345)

# Message to send
message = b'Hello UDP Server'

try:
    # Send message
    sock.sendto(message, server_address)

    # Receive response (buffer size 1024 bytes)
    data, address = sock.recvfrom(1024)
    print(f'Received from server: {data.decode()}')
finally:
    sock.close()
Output
Received from server: Hello UDP Client
⚠️

Common Pitfalls

Common mistakes when creating UDP sockets include:

  • Using socket.SOCK_STREAM instead of socket.SOCK_DGRAM, which creates a TCP socket, not UDP.
  • Not binding the socket to an address when acting as a server, which prevents receiving messages.
  • Assuming UDP guarantees delivery; UDP is connectionless and does not ensure packets arrive.

Here is an example showing the wrong and right way to create a UDP socket:

python
import socket

# Wrong: creates TCP socket
wrong_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Right: creates UDP socket
right_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
📊

Quick Reference

TermDescription
socket.AF_INETIPv4 address family
socket.SOCK_DGRAMUDP socket type (datagram)
sendto(data, address)Send UDP packet to address
recvfrom(buffer_size)Receive UDP packet with buffer size

Key Takeaways

Use socket.socket(socket.AF_INET, socket.SOCK_DGRAM) to create a UDP socket.
UDP sockets send data without establishing a connection, so delivery is not guaranteed.
Bind the socket if you want to receive data as a server.
Avoid using SOCK_STREAM when you need UDP communication.
Use sendto() and recvfrom() methods to send and receive UDP packets.