#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <memory.h>

#include <sys/types.h>

#include <sys/time.h>
#include <sys/socket.h>
#include <sys/resource.h>

#include <netinet/in.h>

#include <arpa/inet.h>
#include <netdb.h>

int TryAccept(int nl) {
    struct sockaddr_in ssin;
    int c, fd, sd, on = 1;

    if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) return -1;

    memset((char *)&ssin, 0, sizeof(struct sockaddr_in));
    ssin.sin_family      = AF_INET;
    ssin.sin_port        = 1080;
    ssin.sin_addr.s_addr = 0;

    setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(int));
    if (bind(sd, (struct sockaddr *)&ssin, sizeof(struct sockaddr_in)) < 0) return -1;
    if (listen(sd, nl) < 0) return -1;

    for (;;) {
	int  len = sizeof (struct sockaddr_in);

	printf("accepting\n");
	if ((fd = accept(sd, &ssin, &len)) < 0) return -1;
	printf("accepted\n");
	read(fd, &c, 1);
	printf("done reading\n");
	close(fd);
    }

    return 0;
}

int main(int argc, char **argv) {
    int ntrys = 10, i;
    if (argc > 1) ntrys = atoi(argv[1]);

    TryAccept(ntrys);
    exit(0);
}
