/*
 * holdconn.c
 * Steve Shah (sshah@planetoid.org)
 * 
 * See floodconn.README for more information.
 *
 * Ignore the forking thing for now... One day I'll finish it.
 *
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/param.h>
#include <sys/uio.h>
#include <netinet/in.h>
#include <unistd.h>

#include <sys/ipc.h>
#include <sys/shm.h>

#include <sys/resource.h>
#include <sys/file.h>
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>

#include <string.h>
#include <errno.h>

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

#define MAX_FD 32768

#define HTTP_GET "GET / HTTP/1.1\n\rHost: 10.10.10.10\n\r\n\r"

int main (int argc, char *argv[])
{
    struct sockaddr_in mysock;
    struct protoent *tcp;
    int port;
    int socket_out[MAX_FD];
    int maxconns;
    int curconn;
    int http_get_len;
    time_t time_start, time_end;
    int total_conns;
    char c;

    if (argc < 4) {
	printf ("usage: %s ip port maxconns\n", argv[0]);
	exit(0);
    }

    port = atoi(argv[2]);
    maxconns = atoi(argv[3]);
    
    http_get_len = strlen(HTTP_GET);

    if (maxconns > MAX_FD) {
        printf ("Max conns is limited to %d\n", MAX_FD);
        exit(0);
    }

    tcp = getprotobyname("tcp");

    bzero((char *)&mysock, sizeof(mysock));
    mysock.sin_family = PF_INET;
    mysock.sin_port = htons(port);
    mysock.sin_addr.s_addr = inet_addr(argv[1]);

    time_start = time(NULL);
    total_conns = 0;

	printf ("Opening connections...\n");	
	for (curconn = 0; curconn < maxconns; curconn++) {
	    
	    socket_out[curconn] = socket (PF_INET, SOCK_STREAM, tcp->p_proto);
	    if (socket_out[curconn] == -1) {
		perror ("Cannot socket");
		exit(0);
	    }
	    
	    if (connect (socket_out[curconn],(struct sockaddr*)&mysock,
			 sizeof(struct sockaddr)) == -1) {
		perror ("Cannot connect");
		exit(0);
	    }
	    
	    total_conns++;
	    
	}

	printf ("Press <ENTER> to close the connections.\n");
	scanf ("%c", &c);

	printf ("Closing connections...\n");	
	for (curconn = 0; curconn < maxconns; curconn++) {
	    
	    close (socket_out[curconn]);
    
	}

	time_end = time(NULL);

    printf ("\n");
    printf ("Time start:        %s", ctime(&time_start));
    printf ("Time end:          %s", ctime(&time_end));
    printf ("Connections:       %d\n", total_conns);

    return 0;
}




