pythonudpbroadcast

Is a UDP broadcast actually a unicast?


If one has to specify a certain port for sending a broadcast, how is it different to a unicast? Isn't the idea of a broadcast, that you can send a packet without specifying its destination in advance?

Example code for a broadcast in python:

def send_udp_broadcast(message, port):
 # Create a UDP socket
 udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

 # Enable broadcasting mode
 udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

 # Set the broadcast address
 broadcast_address = '<broadcast>'
 server_address = (broadcast_address, port)
 udp_socket.sendto(message.encode(), server_address)

I tried performing a broadcast without specifying a port, but it seems not possible.


Solution

  • TL;DR Addresses determine which machine should see the packet. Ports determine which service on a machine should see the packet.


    When a packet is delivered to a network containing the destination, one of two things can happen:

    1. A router can send the packet directly to the interface indicated by the destination address.
    2. The packet is available to anyone on that network, but an interface is supposed to disregard any packet whose destination address does not match its own address.

    In either case, using a broadcast address causes

    1. The router to deliver the packet to every interface on the network
    2. Each interface to recognize the packet as intended for it.

    Once an interface has a packet, the port is used to determine who on the machine should see the packet.