/*********************************************** 2020 Hacker Factor. Public domain, use at your own risk. Neal's quick and easy "let's test everything" test to see how many sockets are available. To compile: gcc -o sockettest sockettest.c To run: ./sockettest ***********************************************/ #include #include #include #include #include #include #include #include void main () { struct rlimit rlim; struct pollfd *fds; int s; int RealMax,Count,SocketCount; // Check the default limits printf("Initial limits\n"); getrlimit(RLIMIT_NOFILE, &rlim); printf(" getrlimit(RLIMIT_NOFILE): soft=%d hard=%d\n", (int)rlim.rlim_cur, (int)rlim.rlim_max); RealMax = sysconf(_SC_OPEN_MAX); printf(" sysconf(_SC_OPEN_MAX): %d\n",RealMax); printf(" sysconf(_SC_STREAM_MAX): %ld\n",(long)sysconf(_SC_STREAM_MAX)); printf(" ulimit(4): %d\n",(int)ulimit(4,0)); // use getrlimit // How many sockets are currently in use? fds = (struct pollfd*)calloc(sizeof(struct pollfd),RealMax); for(s=0; s < RealMax; s++) { fds[s].fd=s; } poll(fds,RealMax,0); Count=0; for(s=0; s < RealMax; s++) { if (!(fds[s].revents&POLLNVAL)) { Count++; } } free(fds); printf("Sockets in use: %d\n",Count); // Now let's actually see how many we can do! SocketCount=0; while(1) { s=socket(AF_INET,SOCK_STREAM,0); if (s >= 0) { SocketCount++; } else { break; } // s==-1 } printf("Managed to create %d sockets before failing.\n",SocketCount); /***** In Tor's ./src/lib/process/restrict.c, they set the soft limit to be the hard limit. Let's try that! *****/ printf("Resetting limits so soft=max\n"); rlim.rlim_cur = rlim.rlim_max; setrlimit(RLIMIT_NOFILE, &rlim); // Now check the limits after the reset... getrlimit(RLIMIT_NOFILE, &rlim); printf(" getrlimit(RLIMIT_NOFILE): soft=%d hard=%d\n", (int)rlim.rlim_cur, (int)rlim.rlim_max); RealMax = sysconf(_SC_OPEN_MAX); printf(" sysconf(_SC_OPEN_MAX): %d\n",RealMax); printf(" sysconf(_SC_STREAM_MAX): %ld\n",(long)sysconf(_SC_STREAM_MAX)); printf(" ulimit(4): %d\n",(int)ulimit(4,0)); // use getrlimit // How many sockets are currently in use? fds = (struct pollfd*)calloc(sizeof(struct pollfd),RealMax); for(s=0; s < RealMax; s++) { fds[s].fd=s; } poll(fds,RealMax,0); Count=0; for(s=0; s < RealMax; s++) { if (!(fds[s].revents&POLLNVAL)) { Count++; } } free(fds); printf("Sockets in use: %d (including the previous %d test)\n",Count,SocketCount); printf(" There should be %d more sockets available.\n",RealMax-Count); // Now let's actually see how many more we can allocate! while(1) { s=socket(AF_INET,SOCK_STREAM,0); if (s >= 0) { SocketCount++; } else { break; } // s==-1 } printf("Managed to create %d sockets before failing.\n",SocketCount); }