Jump to content

Udprec

From Wikitech

Simple UDP receiver, outputs on stdout. Probably written by River.

#include <sys/types.h>
#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

void 
read_and_echo(int sfd, struct sockaddr *cliaddr, int clilen)
{
	int n;
        socklen_t len;
	char msg[BUFSIZ];
	for (;;) {
		len = clilen;
		if ((n = recvfrom(sfd, msg, BUFSIZ, 0, cliaddr, &len)) < 0) {
			perror("recvfrom");
			exit(8);
		}
		write(STDOUT_FILENO, msg, n);
	}
}

int
main(int argc, char *argv[])
{
	if (argc < 2) {
		fprintf(stderr, "usage: %s <port> [host]\n", argv[0]);
		exit(8);
	}

	int sfd;
	struct sockaddr_in servaddr, cliaddr;
	if ((sfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		perror("socket");
		exit(8);
	}
	memset(&servaddr, 0, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
        if (argv[2])
            servaddr.sin_addr.s_addr = inet_addr(argv[2]);
        else
            servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port = htons(atoi(argv[1]));
	if (bind(sfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) {
		perror("bind");
		exit(8);
	}

	read_and_echo(sfd, (struct sockaddr *) &cliaddr, sizeof(cliaddr));
	exit(0);
}