/*    
    Network Speed Server
    Connects to a speed server and checks connection speed

    (C) 2004 Swittech

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation; either version 2
    of the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

    Contact: huntjas2@msu.edu

    Compile with -lwsock32
*/


#include "stdio.h"
#include "winsock.h"
#include <time.h>


#define PORT 1200
#define BACKLOG 10
#define rec_buffer 512000
#define test_size  1024000

int main()
{
    WSADATA wsda;
    WSAStartup(MAKEWORD(1, 1),&wsda);

    printf("Speedcheck Server (C) 2004 Swittech\n");

    SOCKET listen_socket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
    if (listen_socket == INVALID_SOCKET)
    {
        printf("Socket error...\n");
        return 0;
    }

    SOCKADDR_IN server;
    server.sin_addr.s_addr=INADDR_ANY;
    server.sin_port=htons(PORT);
    server.sin_family=AF_INET;

    if(bind(listen_socket, (LPSOCKADDR) &server, sizeof(struct sockaddr)) == SOCKET_ERROR)
    {
        printf("Unable to bind...\n");
        return 0;
    }

    if(listen(listen_socket,BACKLOG) == SOCKET_ERROR)
    {
        printf("Error Listening...\n");
        return 0;
    }

    while (1)
    {

        printf("Waiting for client...");
        SOCKET client_socket = accept(listen_socket,NULL, NULL);

        if (client_socket == INVALID_SOCKET)
        {
            printf("Accept error...\n");
            return 0;
        }

        printf(" connected\n");

        char buffer[rec_buffer];
        int n_bytes;

        long total_bytes = 0;

        clock_t start_time;

        while(1)
        {
            if (total_bytes == 0)
                start_time = clock();

            n_bytes = recv(client_socket, buffer, rec_buffer, 0);

            if (n_bytes < 1) break;

            total_bytes += n_bytes;


            if (total_bytes > test_size)
            {
                clock_t diff = clock() - start_time;

                if (diff > 0)
                    printf("Speed: %4.2fMb/s\n", total_bytes * CLK_TCK * 8 / ((double)diff * (double)1048576));
                else
                    printf("Too fast, increase test size\n");

                start_time = clock();
                total_bytes = 0;
            }
        }

        closesocket(client_socket);
    }

    WSACleanup();
    closesocket(listen_socket);

    return 0;
}
