udp_server.c
e60a9728
 /*
  * $Id$
  */
 
 #include <sys/types.h>
 #include <sys/socket.h>
 #include <netinet/in.h>
 #include <errno.h>
 
 
 #include "udp_server.h"
 #include "config.h"
 #include "dprint.h"
 
 
 int udp_sock;
 
 
 
 int udp_init(unsigned long ip, unsigned short port)
 {
dc862225
 	struct sockaddr_in* addr;
9a3dc64b
 	int optval;
e60a9728
 
dc862225
 	addr=(struct sockaddr_in*)malloc(sizeof(struct sockaddr));
 	if (addr==0){
efeaaf53
 		LOG(L_ERR, "ERROR: udp_init: out of memory\n");
dc862225
 		goto error;
 	}
 	addr->sin_family=AF_INET;
 	addr->sin_port=htons(port);
 	addr->sin_addr.s_addr=ip;
e60a9728
 
 	udp_sock = socket(PF_INET, SOCK_DGRAM, 0);
 	if (udp_sock==-1){
efeaaf53
 		LOG(L_ERR, "ERROR: udp_init: socket: %s\n", strerror());
e60a9728
 		goto error;
 	}
9a3dc64b
 	/* set sock opts? */
 	optval=1;
1b1b19d8
 	if (setsockopt(udp_sock, SOL_SOCKET, SO_REUSEADDR,
cf398313
 					(void*)&optval, sizeof(optval)) ==-1)
9a3dc64b
 	{
efeaaf53
 		LOG(L_ERR, "ERROR: udp_init: setsockopt: %s\n", strerror());
9a3dc64b
 		goto error;
 	}
e60a9728
 
dc862225
 	if (bind(udp_sock, (struct sockaddr*) addr, sizeof(struct sockaddr))==-1){
efeaaf53
 		LOG(L_ERR, "ERROR: udp_init: bind: %s\n", strerror());
e60a9728
 		goto error;
 	}
 
dc862225
 	free(addr);
e60a9728
 	return 0;
 
 error:
dc862225
 	if (addr) free(addr);
e60a9728
 	return -1;
 }
 
 
 
 int udp_rcv_loop()
 {
 	int len;
 	char buf[BUF_SIZE+1];
 	struct sockaddr* from;
 	int fromlen;
 
 	from=(struct sockaddr*) malloc(sizeof(struct sockaddr));
 	if (from==0){
efeaaf53
 		LOG(L_ERR, "ERROR: udp_rcv_loop: out of memory\n");
e60a9728
 		goto error;
 	}
 
 	for(;;){
0c189116
 		fromlen=sizeof(struct sockaddr);
e60a9728
 		len=recvfrom(udp_sock, buf, BUF_SIZE, 0, from, &fromlen);
 		if (len==-1){
efeaaf53
 			LOG(L_ERR, "ERROR: udp_rcv_loop:recvfrom: %s\n", strerror());
e60a9728
 			if (errno==EINTR)	goto skip;
 			else goto error;
 		}
 		/*debugging, make print* msg work */
 		buf[len+1]=0;
 
1b1b19d8
 		receive_msg(buf, len, ((struct sockaddr_in*)from)->sin_addr.s_addr);
 		
e60a9728
 	skip: /* do other stuff */
 		
 	}
1b1b19d8
 	
 	if (from) free(from);
e60a9728
 	return 0;
 	
 error:
1b1b19d8
 	if (from) free(from);
e60a9728
 	return -1;
 }
 
 
 
 /* which socket to use? main socket or new one? */
 int udp_send(char *buf, int len, struct sockaddr*  to, int tolen)
 {
 
 	int n;
 again:
 	n=sendto(udp_sock, buf, len, 0, to, tolen);
 	if (n==-1){
efeaaf53
 		LOG(L_ERR, "ERROR: udp_send: sendto: %s\n", strerror());
e60a9728
 		if (errno==EINTR) goto again;
 	}
 	return n;
 }