#include #include #include #include #include #include #include #include #include #include #include static struct sockaddr_in sin = { .sin_family = AF_INET, .sin_addr = { 0x0100000a }, .sin_port = 0x9a02, }; static void * worker(void *arg) { u_int nsockets = *(u_int *)arg; int *sockets; sockets = malloc(nsockets * sizeof(int)); for (u_int i = 0; i < nsockets; i++) { char s[INET_ADDRSTRLEN]; long r; int rv; sockets[i] = socket(AF_INET, SOCK_DGRAM, 0); if(__predict_false(sockets[i] == -1)) { warn("Socket"); continue; } rv = connect(sockets[i], (struct sockaddr *)&sin, sizeof(sin)); if (__predict_false(rv != 0)) { warn("Connect to %s:%u", inet_ntop(AF_INET, &sin.sin_addr, s, sizeof(s)), ntohs(sin.sin_port)); if (errno == EADDRNOTAVAIL) { warn("Depleted at %u sockets", i); break; } } } return (NULL); } int main(int argc, char *argv[]) { u_int nthreads = (u_int)sysconf(_SC_NPROCESSORS_ONLN); u_int nsockets = 65536; pthread_t *threads; int c; while ((c = getopt(argc, argv, "h:n:t:")) != -1) switch (c) { case 'h': sin.sin_addr.s_addr = inet_addr(optarg); break; case 'n': nsockets = (u_int)strtol(optarg, NULL, 10); break; case 't': nthreads = (u_int)strtol(optarg, NULL, 10); break; default: errx(EX_USAGE, "Usage: %s [-c] [-n sockets] [-t threads]", argv[0]); } printf("%u threads, %u sockets\n", nthreads, nsockets); threads = malloc(nthreads * sizeof(pthread_t)); for (u_int i = 0; i < nthreads; i++) pthread_create(&threads[i], NULL, worker, &nsockets); for (u_int i = 0; i < nthreads; i++) pthread_join(threads[i], NULL); }