Example - Finding the Maximum Number of Open Sockets

Compile and run this example on a machine to find out how many sockets you can open at one time. Beware that on Windows 95/98 machines, this program will eventually take so much CPU time that you may not be able to do anything, including stopping the program! Windows NT systems seem much more well-behaved about this, but they will also tend to bog down a bit while this program is running.

This program is based on Bob Quinn's get_skts.c program. If you find any errors, complain to me, not to him!


get-sockets.cpp

// Borland C++ 5.0: bcc32.cpp getifaces.cpp wsock32.lib
// Visual C++ 5.0:  cl getifaces.cpp wsock32.lib

#include <stdio.h>
#include <winsock.h>
#include <sys/timeb.h>
#include <time.h>

int doit(int, char**)
{
    SOCKET hLastSock;
    long lCurrentTime;

    printf("Working on getting sockets...\n");
    for (int i = 0; /**/; ++i) {
        SOCKET hSock = socket(AF_INET, SOCK_STREAM, 0);
        if (hSock != INVALID_SOCKET) {
            if (i && !(i % 1000)) {
                struct _timeb timebuffer;
                _ftime(&timebuffer);
                char* timeline = ctime(&(timebuffer.time));
                printf("%d sockets so far, at %.19s.%hu %s",
                        i, timeline, timebuffer.millitm, &timeline[20]);
            }

            hLastSock = hSock;
        } 
        else {
            printf("socket(%d) failed.  Err: %d.  Last socket: %d.\n",
                    i, WSAGetLastError(), hLastSock);
            return 0;
        }
    }
    return 0;
}


int main(int argc, char* argv[])
{
    WSAData wsaData;
    if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) {
        return 255;
    }

    int retval = doit(argc, argv);

    WSACleanup();
    return retval;
}

Back to the Advanced Issues page...
Back to the Examples page...


Go to my home page Go to my Important RFC Lists page Go to the main Programming Resources page

Please send updates and corrections to <tangent@cyberport.com>.