/* ex: set ts=2 et: */ /* * Question: * * What is the hard limit of total simultaneous TCP connections on a * Windows XP machine? What is the limiting factor? * * The system which brought this question to mind uses the select() function * call, and so this test will be utilizing select(). * * In this test program we are interested in determining the maximum number * of sockets we can manage with the select() function. * select() depends on fd_set, a set of file-descriptors. * what is the maximum size of an fd_set? * for windows' winsock2's select(), fd_sets are composed of only SOCKETs. * what is the maximum number of SOCKETs creatable via winsock2? * * Answer: * * Interestingly the first hard limit we reach is neither of the above... * it is TCP's 16-bit port number. Since each side or a TCP connection * requires a unique port number allocated from within an operating systems' * TCP stack's port address space, we can not possibly ever have more than * 2^16 (65536) simultaneous TCP connections on a single operating system * instance. * * This is further limited by ports reserved or in use by the TCP standard * and the host operating system. Several ports and port ranges (i.e. port 0) * are reserved by the IANA. Unix-style systems will generally not return a * port in the range of 0-1023 from accept(); I do not know of Windows' * behavior in this regard. Furthermore, any socket-utilizing processes in * existence further limit the address space for local port numbers available * to our application; on my current Windows XP workstation 'netstat -na' * returns several dozen TCP sockets in various states. */ #define FD_SETSIZE 64 * 1024 /* defined *before* winsock2.h is included, obviously. * this can basically be an arbitrary integer; * however if it is very large ensure you don't * overflow your stack! */ #include #define WIN32_LEAN_AND_MEAN #include #include #include int main(void) { static fd_set fd; /* large FD_SETSIZEs will overflow the stack, protect your stack from overflow with static allocation */ long cnt = 0; SOCKET sock; WSADATA data; if (SOCKET_ERROR == WSAStartup(MAKEWORD(2,0), &data)) { perror("WSAStartup"); exit(EXIT_FAILURE); } FD_ZERO(&fd); /* allocate sockets until we produce an error or run out of (16-bit) port address space */ while (SOCKET_ERROR != (sock = socket(AF_INET, SOCK_STREAM, 0)) && cnt <= 0xFFFF) { cnt++; if (0 == (cnt & (cnt-1))) printf("socket[%ld]=%d\n", cnt, (int)sock); FD_SET(sock, &fd); } printf("allocated %ld sockets before limit reached\n", cnt); return 0; }