def mcast_receiver(port, mcgroup=MC_GROUP):
    """Open a UDP socket, bind it to a port and select a multicast group.
    """

    if _is_broadcast_group(mcgroup):
        group = None
    else:
        group = mcgroup

    # Create a socket
    sock = socket(AF_INET, SOCK_DGRAM)

    # Allow multiple copies of this program on one machine
    # (not strictly needed)
    sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    if group:
        sock.setsockopt(SOL_IP, IP_MULTICAST_TTL, TTL_LOCALNET)  # default
        sock.setsockopt(SOL_IP, IP_MULTICAST_LOOP, 1)  # default

    # Bind it to the port
    sock.bind(('', port))

    # Look up multicast group address in name server
    # (doesn't hurt if it is already in ddd.ddd.ddd.ddd format)
    if group:
        group = gethostbyname(group)

        # Construct binary group address
        bytes_ = [int(b) for b in group.split(".")]
        grpaddr = 0
        for byte in bytes_:
            grpaddr = (grpaddr << 8) | byte

        # Construct struct mreq from grpaddr and ifaddr
        ifaddr = INADDR_ANY
        mreq = struct.pack('!LL', grpaddr, ifaddr)

        # Add group membership
        sock.setsockopt(IPPROTO_IP, IP_ADD_MEMBERSHIP, mreq)

    return sock, group or '<broadcast>'
Open a UDP socket, bind it to a port and select a multicast group.