/*
 * http-dump: inspect http commands
 *
 * Eleri Cardozo, 1999.
 * 
 * Acrescentado <stdlib.h> por Ricardo Gudwin 2013, para evitar mensagem de erro sobre exit(x)
 */

/*
 * Include Files.
 */
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>


/*
 * Main
 */
main(argc, argv)
int argc;
char **argv;
{
    unsigned short port;       /* port server binds to                  */
    char buf[1024];            /* buffer for sending and receiving data */
    struct sockaddr_in client; /* client address information            */
    struct sockaddr_in server; /* server address information            */
    int s;                     /* socket for accepting connections      */
    int ns;                    /* socket connected to client            */
    int namelen;               /* length of client name         	*/
    int msglen;                /* length of the received message        */
    int i;
 

    /*
     * Check arguments. Should be only one: the port number to bind to.
     */

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

    /*
     * First argument should be the port.
     */
    port = (unsigned short) atoi(argv[1]);

    /*
     * Get a socket for accepting connections.
     */
    if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        perror("Socket()");
        exit(2);
    }

    /*
     * Bind the socket to the server address.
     */
    server.sin_family = AF_INET;
    server.sin_port   = htons(port);
    server.sin_addr.s_addr = INADDR_ANY;

    if (bind(s, (struct sockaddr *)&server, sizeof(server)) < 0)
    {
       perror("Bind()");
       exit(3);
    }

    /*
     * Listen for connections. Specify the backlog as 5.
     */
    if (listen(s, 5) != 0)
    {
        perror("Listen()");
        exit(4);
    }

    /*
     *  Loop forever
     */
    printf("\n%s accepting connections from HTTP clients.", argv[0]);
    fflush(stdout);

    while (1) {

    /*
     * Accept a connection.
     */
    namelen = sizeof(client);
    if ((ns = accept(s, (struct sockaddr *)&client, &namelen)) == -1)
    {
        perror("Accept()");
        break;
    }

    /*
     * Receive the message on the newly connected socket.
     */
    if ((msglen = recv(ns, buf, sizeof(buf), 0)) == -1)
    {
        perror("Recv()");
        break;
    }

    
    /* 
     * Print what was received and close connection
     */
    printf("\n\nMessage received:\n");
    for(i = 0; i < msglen; i++) printf("%c", buf[i]);
    fflush(stdout);
    close(ns);

    }  /* loop ends here */

    close(s); 
    printf("Server ended on error\n");
    exit(5);
}


