#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <math.h>
#include <string.h>
#include <signal.h>

#define MAXLINE 4096
#define BUFFER 4000
#define LISTENQ 2
#define SA struct sockaddr

#define printsocket(s) printf("%s, %d\n", inet_ntoa(s.sin_addr), \
				   (int) ntohs(s.sin_port));

int
main (int argc, char **argv)
{
	pid_t pid;

        if( (pid = fork() ) < 0 ) {
                printf( "Error forking to the background.\n" );
                exit(1);
        }

        if( pid == 0 ) { // start the child process
		if ( argc==4 && !strncmp(argv[1],"-c",2) )
			return ucli(&argv[2]);
		else {
			printf(" ** Usage: a.out -c <IP address> <Port Num>\n");
			exit(1);
		}
	} else { // Kill the parent process
		exit(0);
	}
}

int
ucli(char **sktinfo)
{
	int sktid;
	struct sockaddr_in servaddr;
	char bufread[BUFFER];

	if ( (sktid =socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		printf(" ** Unable to get socket id\n");
		exit(1);
	}

	bzero(&servaddr, sizeof (servaddr));
	servaddr.sin_family = AF_INET;
	if ( (servaddr.sin_addr.s_addr = inet_addr(sktinfo[0])) < 0) {
		printf(" ** Unable to convert IP address\n");
		exit(1);
	}
	servaddr.sin_port = htons (atoi(sktinfo[1]));

	while( 1 ) {
		int i_retval = system( "dmesg -c > /root/dmesg.log" );
		if( i_retval == -1 ) {
			printf( "System command failed to fork, exiting...\n" );
			exit( 1 );
		}
		
		FILE *fp = NULL;
		if( !fp ) {
			fp = fopen( "/root/dmesg.log", "r" );
		}

		while( !feof( fp ) ) {
			int n = fread( bufread, sizeof(char), BUFFER, fp );
			sendto(sktid, bufread, n, 0, (SA *) &servaddr, sizeof(servaddr));
		}
		fclose( fp );
		sleep(5);
	}

	return(0);
}
