---- # scan.tcl - Copyright (C) 2003 Pat Thoyts # # Scan for services using TCP. # # This illustrates use of the writable fileevent handler # # $Id: 9829,v 1.4 2005-04-30 06:00:35 jcw Exp $ # Scan a subnet for servers on the specified port. # proc scan {base port} { global hosts nodes catch {unset hosts} array set hosts {} for {set ip 1} {$ip < 250} {incr ip} { connect "$base.$ip" $port } set nodes $ip } # Connect asynchronously to a TCP service on the given port. # Once connected (or once we fail) the handler will be called. # If a host is up it returns pretty quickly. So use a short timout # to give up on the others. proc connect {host port} { set s [socket -async $host $port] fileevent $s writable [list ::connected $host $port $s] after 2000 [list shutdown $s] return } # Connection handler for the port scanner. This is called both # for a successful connection and a failed connection. We can # check by trying to operate on the socket. A failed connection # raises an error for fconfigure -peername. As we have no other # work to do, we can close the socket here. # proc connected {host port sock} { global hosts fileevent $sock writable {} set r [catch {fconfigure $sock -peername} msg] if { ! $r } { set hosts($host) $msg } shutdown $sock } proc shutdown {sock} { global nodes incr nodes -1 catch {close $sock} } proc wait {varname} { while {[set $varname] > 1} { vwait $varname } } if {$::tcl_interactive} { puts "call 'scan 192.168.0 port' then examine the hosts array" } else { eval [list scan] $argv wait ::nodes parray hosts } ---- See also [fileevent] See also [Detecting Port Scans in Tcl] ---- [Zarutian] 29 april 2005: this might be useful for finding other peers in peer-to-peer applications. ---- [Category Application] | [Category Internet]