import socket

def listen_for_broadcast():
    # Define the port to listen on
    PORT = 43210

    # Create a UDP socket
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
        # Allow the socket to reuse the address
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        
        # Enable broadcasting
        s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        
        # Bind the socket to all available interfaces and the specified port
        s.bind(("", PORT))
        
        print(f"Listening for broadcast messages on port {PORT}")

        # Buffer size for receiving data
        buffer_size = 4096
        
        while True:
            try:
                # Receive data from the socket
                data, addr = s.recvfrom(buffer_size)
                # Print the received message and the sender's address
                print(f"Received message from {addr}:")
                print(f"Message: {data.decode('utf-8', errors='replace')}")  # Decode with error handling
                
            except UnicodeDecodeError as e:
                # Handle cases where the message can't be decoded properly
                print(f"Received non-UTF-8 data from {addr}: {e}")
                print(f"Raw data: {data.hex(' ')}")
                
            except Exception as e:
                print(f"An error occurred: {e}")
                break

if __name__ == "__main__":
    listen_for_broadcast()
