#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <signal.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>

struct sockaddr_in msin;
int s;

#define  IPPORT 54321

Error(c, s)
	char           *c;
	int             s;
{
	perror(c);
	close(s);
	exit(1);
}

void BrokenPipe(Signal, Code, SignalContextPtr)
	int             Signal, Code;
	struct sigcontext *SignalContextPtr;
{
	signal(SIGPIPE, BrokenPipe);
	return;
}

main(argc, argv)
	int             argc;
	char           *argv[];
{
	struct ip_mreq  mreq;
	int             cc, ccb, ch;
	char            buf[10240];
	int             len;
	int             one = 1;
	extern char	*optarg;
	extern int	optind;

	mreq.imr_interface.s_addr = htonl(INADDR_ANY);
	signal(SIGPIPE, BrokenPipe);
	while ((ch = getopt(argc, argv, "i:")) != -1)
		switch(ch) {
		    case 'i':
			mreq.imr_interface.s_addr = inet_addr(optarg);
			break;
		}
	argc -= optind;
	argv += optind;
	if (argc != 1) {
		fprintf(stderr, "groupe manque\n");
		exit(-1);
	}
	if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) {
		perror("socket");
		exit(1);
	}
	(void) setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &one, sizeof(one));

	msin.sin_family = AF_INET;
	msin.sin_port = htons(IPPORT);
	if (bind(s, (struct sockaddr *)&msin, sizeof(msin)) < 0) {
		perror("bind");
		exit(1);
	}

	mreq.imr_multiaddr.s_addr = inet_addr(*argv);
	if (setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP,
		       &mreq, sizeof(mreq)) < 0) {
		perror("setsockopt IP_ADD_MEMBERSHIP");
		return (0);
	}
	for (;;) {
		cc = read(s, buf, 10240);
		if (cc < 0) {
			perror("read socket");
			return (cc);
		} else if (cc > 0) {
			ccb = write(1, buf, cc);
			if (ccb != cc)
				perror("write file");
			fprintf(stderr, "<-%d-\n", cc);
		} else {
			fprintf(stderr, "..\n");
			return (0);
		}
	}
}
