#include <stdio.h>

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

int main(int argc, char *argv[])
{
	int fd, err;
	struct addrinfo hints, *res, *aicurr;
	char *hostname, *service;
	char buf[1024];

	// default hostname / port
	hostname = "localhost";
	service = "daytime";

	switch(argc) {
		case 3:
			service = argv[2];
		case 2:
			hostname = argv[1];
		default:
			break;
	}

	memset(&hints, '\0', sizeof(hints));

	hints.ai_family = PF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	//hints.ai_flags = AI_PASSIVE;

	err = getaddrinfo(hostname, service, &hints, &res);
	if (err) {
		fprintf(stderr, "getaddrinfo failed: %s\n", gai_strerror(err));
		exit(2);
	}

	for (aicurr = res; aicurr != NULL; aicurr = aicurr->ai_next) {
		fd = socket(aicurr->ai_family, aicurr->ai_socktype,
				aicurr->ai_protocol);
		if (fd < 0) {
			perror("socket");
			fprintf(stderr, "Trying next address in list....\n");
			continue;
		}

		err = connect(fd, aicurr->ai_addr, aicurr->ai_addrlen);
		if (err) {
			perror("connect");
			fprintf(stderr, "Trying next address in list....\n");
			continue;
		}

		break;
	}

	if (aicurr == NULL) {
		fprintf(stderr, "No addresses worked.... bailing out.\n");
		exit(3);
	}

	// connection established... receive text...
	err = read(fd, buf, sizeof(buf));

	if (err > 0) {
		printf("Received %d bytes:\n%s\n", err, buf);
	} else if (err < 0) {
		perror("read");
	} else {
		printf("Received EOF\n");
	}

	close(fd);

	if (err < 0)
		return err;

	return 0;
}

