#include <sys/param.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>

#include <netinet/in.h>
#include <arpa/inet.h>

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

int main(int argc, char *argv[]) {
	char buffer[1024];
	int listening_fd,
		connection_fd,
		port,
		size;
	struct sockaddr_in local_address,
						remote_address;
	struct timeval tv;

	if (argc != 2) {
		fprintf(stderr, "usage: %s port\n", getprogname());
		exit(1);
	} else {
		port = atoi(argv[1]);
	}

	/* create socket */
	if ((listening_fd = socket(PF_INET, SOCK_STREAM, 0)) == -1) {
		err(1, "socket");
	}

	/* allow us to rebind even if old clients are still hanging around */
	size = 1; /* borrow memory for a second */
	if (setsockopt(listening_fd, SOL_SOCKET, SO_REUSEADDR, &size, sizeof(size)) != 0) {
		err(1, "setsockopt");
	}

	/* describe our end of the connection */
	bzero(&local_address, sizeof(local_address));
	local_address.sin_family = AF_INET;
	local_address.sin_addr.s_addr = htonl(INADDR_ANY);
	local_address.sin_port = htons(port);

	/* bind the socket to the address */
	if (bind(listening_fd, (struct sockaddr *)&local_address, sizeof(local_address)) == -1) {
		err(1, "bind");
	}

	/* make it a listening port */
	if (listen(listening_fd, -1) != 0) {
		err(1, "listen");
	}

	/* accept connections */
	for (;;) {
		size = sizeof(remote_address);
		if ((connection_fd = accept(listening_fd, (struct sockaddr *)&remote_address, &size)) == -1) {
			err(1, "accept");
		}

		printf("connected...\n");

		/* set up timeouts */
		tv.tv_sec = 15L;
		tv.tv_usec = 0L;
		if (setsockopt(connection_fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) != 0) {
			err(1, "setsockopt");
		}
		if (setsockopt(connection_fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) != 0) {
			err(1, "setsockopt");
		}

		/* do a bit of reading and writing */
#define STRING "hello\n"
		if (write(connection_fd, STRING, sizeof(STRING)) == -1) {
			err(1, "write");
		}
#undef STRING

		if (read(connection_fd, buffer, sizeof(buffer)) == -1) {
			warn("read");
			goto failure;
		} else {
			printf("received %s", buffer);
		}

#define STRING "goodbye\n"
		if (write(connection_fd, STRING, sizeof(STRING)) == -1) {
			err(1, "write");
		}
#undef STRING

failure:
		if (close(connection_fd) == -1) {
			err(1, "close");
		}

		printf("disconnected...\n");
	}

	return 0;
}	
