> 1 <

Автор Сообщение

misha

Moderators


Статус

1275 сообщений
http://racket-lang.org/
Где: Yemen
Род занятий:
Возраст:

#3924   2011-02-13 18:32 GMT+3 часа(ов)      
Простой многопоточный сканер TCP портов.
#lang racket
 
(define (tcp-open-ports host from to
#:max-threads [max-threads 50]
#:wait-sec [wait-sec 2])
(when (> from to)
(set! to from))
(when (< max-threads 10)
(set! max-threads 10))
;(when (> max-threads 100)
; (set! max-threads 100))
(when (<= wait-sec 0)
(set! wait-sec 0.5))
(letrec
([cust (make-custodian)]
[result null]
[get-port
(let ([port (sub1 from)]
[sem (make-semaphore 1)])
(lambda()
(semaphore-wait sem)
(set! port (add1 port))
(semaphore-post sem)
port))]
[work
(lambda()
(let ([port (get-port)])
(when (<= port to)
(let ([thd
(thread
(lambda()
(with-handlers ([exn:fail:network? void])
(let-values ([(in out)
(tcp-connect host port)])
(close-output-port out)
(close-input-port in)
(set! result (cons port result))))))])
(unless (sync/timeout wait-sec thd)
(kill-thread thd))
(work)))))]
[threads
(parameterize ([current-custodian cust])
(custodian-limit-memory cust (* 2 1024 1024))
(build-vector
(if (> max-threads
(add1 (- to from)))
(add1 (- to from))
max-threads)
(lambda(n) (thread work))))])
(do() [(zero? (vector-count thread-running? threads))
(custodian-shutdown-all cust)
(sort result <)]
(sleep 0.1))))
 
> (time (tcp-open-ports "127.0.0.1" 20 4000 #:max-threads 100 #:wait-sec 0.5))
cpu time: 19328 real time: 20344 gc time: 235
'(135 445 1025 2869 3306)
> 1 <


Онлайн :

0 пользователь(ей), 21 гость(ей) :




Реклама на сайте: