#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <errno.h>
#include <netdb.h>

#define XPLANE_PORT 49001
#define BUFSZ 512
#define STEP 16

int
get_udp_listen_socket(unsigned short port)
{
	int s;
	struct sockaddr_in sa;
	
	
	s = socket(AF_INET, SOCK_DGRAM, 0);
	if (s == -1)
		return -1;
	
	sa.sin_family = AF_INET;
	sa.sin_port = htons(port);
	sa.sin_addr.s_addr = INADDR_ANY;
	
	if ( bind(s, (struct sockaddr *) &sa, sizeof(sa)) == -1 )
		return -1;

	
	return s;
}

void
hexdump(unsigned char *buf, int buflen)
{
	int i, c, s;
	for (i = 0; i < buflen; i+= STEP)
	{
		c = 0;
		//printf("%8.8x: ", i);
		while ( (c < STEP) && (i+c < buflen) )
			printf("%2.2x ", buf[i+c++]);
		
		s = 1 + (STEP - c);
		while (s--)
			printf("   ");
		
		c = 0;
		while ( (c < STEP) && (i+c < buflen) )
		{
			printf("%c", isprint(buf[i+c]) ? buf[i+c] : '.' );
			c++;
		}
			
		printf("\n");
	}
}

main()
{
	unsigned char buf[BUFSZ];
	int rc;
	struct sockaddr_in sa;
	socklen_t l = sizeof(sa);
	int s = get_udp_listen_socket(XPLANE_PORT);
	if (s == -1)
	{
		perror("xpdatarecv");
		exit(-1);
	}
	
	printf("Ready.\n");
	while ( (rc = recv(s, buf, BUFSZ, 0)) > 0 )
	{
		printf("Received bytes: %d\n", rc);
		hexdump(buf, rc);
	}

	close(s);
}








