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.
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:
In either case, using a broadcast address causes
Once an interface has a packet, the port is used to determine who on the machine should see the packet.