#include <err.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>

int main()
{
	struct addrinfo hints;
	memset(&hints, 0, sizeof(hints));
	hints.ai_family = AF_INET;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = 0;
	hints.ai_protocol = 0;

	struct addrinfo *result;
	int ret = getaddrinfo("127.0.0.1", "24242", &hints, &result);
	if (ret == -1) {
		err(EXIT_FAILURE, "failed getting addr info");
	}

	int tcp_sock = -1;

	for (struct addrinfo *rp = result; rp != NULL; rp = rp->ai_next) {
		int s = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
		if (s == -1)
			continue;

		if (connect(s, rp->ai_addr, rp->ai_addrlen) != -1) {
			tcp_sock = s;
			break;
		}

		close(s);
	}

	freeaddrinfo(result);
	if (tcp_sock == -1) {
		err(EXIT_FAILURE, "couldn't connect to socket");
		return -1;
	}

	int c;
	while ((c = fgetc(stdin)) != EOF) {
		char cb = c;
		int ret = write(tcp_sock, &cb, 1);
		if (ret == -1) {
			err(EXIT_FAILURE, "failed writing to socket");
		}

		if (cb == '\n') {
			char buf[4096];
			ret = read(tcp_sock, buf, 4096);
			if (ret == -1) {
				printf("Error\n");
				break;
			}

			if (ret == 0) {
				printf("Closed socket\n");
				break;
			}
			printf("%s\n", buf);
		}
	}

	close(tcp_sock);
}
