Newer
Older
src / c / udpmsg / udpmsgd.c
/*
 * udpmsgd: recieve messages via UDP
 */

/*
 * Copyright (c) 2006 Andreas Jaggi <andreas.jaggi@waterwave.ch>
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdlib.h>
#include <netinet/in.h>
#include <errno.h>

#include "udpmsg.h"

const char usagemsg[] =
	"usage: udpmsgd\n"
	"\n"
	" options: udpmsgd -v    show version\n"
	"          udpmsgd -h    display this help\n"
	"          udpmsgd -l    display (BSD) license\n"
	;

const char versionmsg[] = "udpmsgd 0.2\n";

void usage ( );
void version ( );

int main ( int argc, char* argv[] ) {
	int sock;
	int tmp;
	struct sockaddr_in *from;
	struct sockaddr_in *local_addr;
	socklen_t *fromlen;
	char msg[UDPMSG_LEN+1];

	sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if ( sock < 0 ) {
		showerror("socket");
		exit(-1);
	}

	local_addr = alloca(sizeof(struct sockaddr_in));
	local_addr->sin_family = AF_INET;
	local_addr->sin_port = UDPMSG_PORT;
	local_addr->sin_addr.s_addr = INADDR_ANY;

	tmp = bind(sock, (struct sockaddr*)local_addr, sizeof(struct sockaddr_in));
	if ( tmp < 0 ) {
		showerror("bind");
		exit(-1);
	}

	while ( 1 ) {
		tmp = recvfrom(sock, msg, UDPMSG_LEN, 0, (struct sockaddr*)from, fromlen);
		if ( tmp < 0 ) {
			showerror("recvfrom");
			exit(-1);
		}
		msg[tmp] = '\n';
		write(1,msg,tmp+1);
	}

	tmp = close(sock);
	if ( tmp < 0 ) {
		showerror("close");
		exit(-1);
	}

	exit(0);
}

void usage ( ) {
	write(1, usagemsg, strlen(usagemsg));
}

void version ( ) {
	write(1, versionmsg, strlen(versionmsg));
}