C - UDP sink example

8. March 2012 20:12

 

This is a short example in C on linux which will open a socket and listen on a udp port for data.

 

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

#include <arpa/inet.h>
#include <sys/socket.h>

int verbose = 0;

void print_usage(FILE *fp, char *app) {
	fprintf(fp, "Usage: %s <port>\n", app);
	fprintf(fp, "\n");
	fprintf(fp, "  -h        Print this help\n");
	fprintf(fp, "\n");
	fprintf(fp, "Example: %s 5000\n", app);
	fprintf(fp, "\n");
}

int main(int argc, char **argv) {
	int c;
	int sockfd;
	struct sockaddr_in in;
	socklen_t in_size = sizeof(in);
	char buf[65535];
	int port = 0;
	
	while(( c = getopt(argc, argv, "hv")) != -1) {
		switch(c) {
			case 'h':
				print_usage(stdout, argv[0]);
				exit(EXIT_FAILURE);
				break;
			case 'v':
				verbose++;
				break;
			default:
				break;
		}
	}
	
	if (optind < argc) {
		port = atoi(argv[optind]);
		optind++;
	} else {
		print_usage(stderr, argv[0]);
		exit(EXIT_FAILURE);
	}

	if (port == 0 || port > 65535) {
		fprintf(stderr, "%d is an invalid port\n", port);
		exit(EXIT_FAILURE);
	}

	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	if (sockfd < 0) {
		perror("socket");
		exit(EXIT_FAILURE);
	}

	in.sin_family = AF_INET;
	in.sin_port = htons(port);
	in.sin_addr.s_addr = INADDR_ANY;

	if (bind(sockfd, (struct sockaddr *) &in, sizeof(in)) < 0) {
		perror("bind");
		exit(EXIT_FAILURE);
	}

	while(1) {
		int ret = recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *) &in, &in_size);

		if (ret < 0) {
			perror("recvfrom");
			continue;
		}
		if (verbose)
			printf("Recived: %d Bytes From %s:%d\n", ret, inet_ntoa(in.sin_addr), ntohs(in.sin_port));

	}

	return 0;
}

E-mail Kick it! DZone it! del.icio.us Permalink