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

int main()
{
	int sock;
	uint16_t port=2234;
	struct sockaddr_in server, client;
	size_t size;
	char message1[1500];
	char message2[1500];
	int len;

	sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
	if( sock == -1 )
	{
		printf("Error create socket\n");
		exit(0);
	}

	client.sin_family = AF_INET;
	client.sin_port = 0;
	client.sin_addr.s_addr = htonl (INADDR_LOOPBACK);

	if( bind( sock, (struct sockaddr*) &client, sizeof(client)) == -1 )
	{
		printf("Error bind socket %d\n", errno);
		exit(0);
	}

	server.sin_family = AF_INET;
	server.sin_port = htons (port);
	server.sin_addr.s_addr = htonl (INADDR_LOOPBACK);

	if (0 > connect (sock, (struct sockaddr *) &server, sizeof (server)))
	{
  		printf ("err: connect (client) %d\n", errno);
  		exit (0);
	}
	
	while(1)
	{
		printf("\ninput-message>");
		fgets(message1, 1500, stdin);
		len=strlen(message1)+1;
		size = sizeof(client);

		len = write (sock, message1, len);

		if( len < 0 )
		{
			printf("Error send response\n");
			exit(0);
		}
		printf ("\nClient: sent message: %s\n", message1);

		len = read (sock, message2, 1500);	

		if( len < 0 )
		{
			printf("Error receive message\n");
			exit(0);
		}
		printf ("\nClient: got message: %s\n", message2);
		
	}
}
 
