import socket
import struct


def make_udp_sock() -> socket.socket:
    """Make a suitable udp socket to listen for device discovery requests.

    I would *love* to get rid of this function and just use the built-in
    options to `create_datagram_endpoint` (e.g. `allow_broadcast` with
    appropriate local and remote addresses), but having no luck. Would be
    thrilled if someone can figure this out in a better way than this or
    <https://github.com/n8henrie/fauxmo/blob/c5419b3f61311e5386387e136d26dd8d4a55518c/src/fauxmo/protocols.py#L149>.

    Returns:
        Socket suitable for responding to multicast requests

    """
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    reuseport = getattr(socket, "SO_REUSEPORT", None)
    if reuseport:
        sock.setsockopt(socket.SOL_SOCKET, reuseport, 1)

    sock.bind(("", 1900))

    group = socket.inet_aton("239.255.255.250")
    mreq = struct.pack("4sL", group, socket.INADDR_ANY)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)

    return sock