/*    
    Network Speed Client
    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 "stdlib.h"
#include "winsock.h"
#include <time.h>

#define PORT 1200
#define packet_size 2048
#define num_packets 500
#define test_size  packet_size * num_packets

void main(int argc, char *argv[])
{
    WSADATA wsda;
    WSAStartup(MAKEWORD(1, 1),&wsda);

    char hostname[1024];

    char packet[packet_size];

    for (int i = 0; i < packet_size; i++)
        packet[i] = rand()%256;

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

    if (argc != 2)
    {
        printf("Enter hostname: ");
        scanf("%s", hostname);
    }
    else
        strcpy(hostname, argv[1]);

    LPHOSTENT hostent;

    hostent=gethostbyname(hostname);

    if (!hostent)
    {
        fprintf(stderr,"Host name error\n");
        exit(1);
    }

    /* create the socket */
    SOCKET sockfd;

    sockfd = socket(AF_INET,SOCK_STREAM, IPPROTO_TCP);

    if (sockfd == INVALID_SOCKET)
    {
        printf("Socket error\n");
        exit(1);
    }

    /* setup address information */
    SOCKADDR_IN server;

    server.sin_addr=*((LPIN_ADDR)*hostent->h_addr_list);
    server.sin_port=htons(PORT);
    server.sin_family=AF_INET;

    if(connect(sockfd,(LPSOCKADDR)&server, sizeof(struct sockaddr)) == SOCKET_ERROR)
    {
        printf("Connection time out\n");
        exit(1);
    }

    printf("Connected, running test\n");

    // conduct the test
    while(1)
    {
        clock_t start_time = clock();

        for (int i = 0; i < num_packets; i++)
            if (send(sockfd,packet,packet_size,0) == SOCKET_ERROR)
            {
                printf("Send error\n");
                exit(1);
            }

        clock_t diff = clock() - start_time;

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

    closesocket(sockfd);
    WSACleanup();
}

