rocksock_readline: change semantics: trailing \n is removed
[rofl0r-rocksock.git] / examples / rocksock_test.c
blob634163d239fd6c2f99b3f5b4c1f19bab3390a956
1 // use rcb to compile: rcb rocksock_test.c
3 /*
5 * author: rofl0r
7 * License: LGPL 2.1+ with static linking exception
12 #include <stdio.h>
13 #include <string.h>
14 #include <stdlib.h>
15 #include <pthread.h>
16 #include <errno.h>
17 #include <time.h>
18 #include "../rocksock.h"
20 //RcB: LINK "-lpthread"
22 typedef struct {
23 char host[16];
24 int port;
25 int status;
26 } threaddata;
28 static int done = 0;
29 static pthread_mutex_t mutex;
31 static void* scanHost(void* arg) {
32 threaddata* d = arg;
33 rocksock skt;
34 rocksock* soc = &skt;
35 rocksock_init(soc);
36 rocksock_set_timeout(soc, 1500);
38 if (!rocksock_connect(soc, d->host, d->port, 0)){
39 d->status = 1;
40 } else {
41 //printf("%s\n", soc->lasterror.errormsg);
42 d->status = 0;
45 rocksock_disconnect(soc);
46 rocksock_clear(soc);
48 pthread_mutex_lock(&mutex);
49 done++;
50 pthread_mutex_unlock(&mutex);
51 return 0;
54 int running(pthread_t* t, int max) {
55 int res = 0, i = 0;
56 for (; i <= max; i++) {
57 if (t[i]) res++;
59 return res;
62 int joinThreads(pthread_t* threads, int max) {
63 void* exitstate;
64 int i = 0;
65 for(;i<max;i++) {
66 if (threads[i]) {
67 if (!pthread_join(threads[i], &exitstate)) {
68 threads[i] = 0;
69 free(exitstate);
73 return 0;
76 int scanRange(const char *ip, int port, int max_threads) {
78 int maxthreads = max_threads > 254 ? 254 : max_threads;
79 pthread_t threads[255] = {0};
80 threaddata data[255] = {0};
82 pthread_attr_t attr;
83 size_t stack;
84 pthread_attr_init(&attr);
85 pthread_attr_getstacksize(&attr, &stack);
86 stack = 32768;
87 pthread_attr_setstacksize(&attr, stack);
89 pthread_mutex_init(&mutex, NULL);
91 volatile int x = 1;
92 while(done < 254) {
93 while(x < 255 && running((pthread_t*) threads, x) < maxthreads) {
94 threaddata* d = &data[x];
95 snprintf(d->host, sizeof(d->host), "%s.%d", ip, x);
96 d->port = port;
97 d->status = -1;
98 if (!pthread_create(&threads[x], &attr, scanHost, &data[x])) {
99 x++;
101 else {
102 break;
105 joinThreads(threads, x);
108 joinThreads(threads, x);
110 pthread_attr_destroy(&attr);
112 int i = 0;
113 for (; i < 255; i++) {
114 if (data[i].status > 0) dprintf(1, "%s\n", data[i].host);
117 pthread_mutex_destroy(&mutex);
118 return 0;
121 int main(int argc, char** argv) {
122 if (argc < 4) {
123 dprintf(2, "multithreaded subnet portscanner\n"
124 "inv. syntax\n"
125 "%s 127.0.0 22 16\n"
126 "subnetA port maxthreads\n", argv[0]);
127 exit(1);
130 int port = atoi(argv[2]);
131 char* ip = argv[1];
132 int maxthreads = atoi(argv[3]);
134 scanRange(ip, port, maxthreads);
135 return 0;