#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

#define HOST "localhost"
#define PORT "12345"


int main(int argc, char *argv[])
{
	int fd, len;
	char buf[1024];

	fd = createconnsocket(HOST, PORT);
	if (fd < 0) {
		fprintf(stderr, "ERROR: Failed to connect to %s on port %s\n", HOST, PORT);
		exit(fd);
	} else {
		snprintf(buf, sizeof(buf), "lala baba fafa\n");
		printf("Sending server: %s\n", buf);
		len = write(fd, buf, strlen(buf)+1);
		printf("Waiting for response...\n");
		len = read(fd, buf, sizeof(buf)-1);
		if (len < 0) {
			fprintf(stderr, "ERROR: read() failed. Aborting!\n");
			exit(1);
		}
		
		buf[len] = '\0'; /* stringslut är bra att ha (ifall det inte redan finns) */
		printf("Server sent: %s\n", buf);
		close(fd);
	}

	return 0;
}

int createconnsocket(char *host, char *port)
{
	int fd, err;
	struct addrinfo hints, *res, *curr;

	memset(&hints, 0, sizeof(hints));
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_protocol = IPPROTO_TCP;

	err = getaddrinfo(host, port, &hints, &res);
	if (err) {
		fprintf(stderr, "ERROR: getaddrinfo() failed: %s\n", gai_strerror(err));
		return -1;
	}

	for (curr = res; curr != NULL; curr = curr->ai_next) {
		fd = socket(curr->ai_family, curr->ai_socktype, curr->ai_protocol);
		if (fd < 0) {
			continue;
		}

		err = connect(fd, curr->ai_addr, curr->ai_addrlen);
		if (err) {
			continue;
		}

#ifdef PRINT_CONNECTED_HOST_INFO
		char host[NI_MAXHOST], serv[NI_MAXSERV];

		err = getnameinfo(curr->ai_addr, curr->ai_addrlen,
				host, NI_MAXHOST,
				serv, NI_MAXSERV,
				NI_NUMERICHOST);
		printf("Connection to %s:%s established....\n", host, serv);
#endif

		/* listening socket successfully created! */
		break;
	}

	if (curr == NULL) {
		fprintf(stderr, "ERROR: no matches from given hints worked.... failed to create socket!\n");
		fd = -2;
	}

	freeaddrinfo(res);

	return fd;
}

