<<

Winsock Programmer's FAQ
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.

Note that this program only tells you how many sockets you can create at one time. It will not tell you how many sockets you can have in use at one time. There is an item in the main FAQ that covers the issue in detail.

This program is based on Bob Quinn's get_skts.c program.


get-sockets.cpp

#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;
}


<< Get the Username Articles >>
Last modified on 29 April 2000 at 15:52 UTC-7 Please send corrections to tangent@cyberport.com.
< Go to the main FAQ page
<< Go to my Programming pages
<<< Go to my Home Page