ipscan

KL 2008-05-02: This example script executed as client scans the IP address range 192.168.0.2 to 192.168.0.255 for an server (which is the same script executed as server) If you use windows XP with SP2 (or Vista) this script won't work correctly if the server IP is larger than 192.168.0.10 (e.g. 192.168.0.11). See socket for reasons.

Principle

  1. To achieve a rapid scan process a whole bunch of sockets is opened first (e.g. 254 sockets from 192.168.0.2 to 192.168.0.255)
  2. All the successfully opened sockets are scanned for the response SERVER_OK
  3. All sockets are close again

Code

 proc scan_ip {start_ip end_ip} {
 global globals
 set curr_ip 192.168.0.$start_ip
 set end_ip_section 192.168.0.$end_ip
  while {$curr_ip != $end_ip_section} {
    #open the whole bunch of sockets (normally 255)
    if {![catch {set sock [socket  -async $curr_ip $globals(client_server_port)]}]} {
      fconfigure $sock -blocking 0 -buffering line
      append ip_list "$sock $curr_ip "  
    puts "testing:$curr_ip"
    }
    incr start_ip
    set curr_ip 192.168.0.$start_ip
  }
 after 100
 #check the successfully opened sockets if there is an server behind 
 foreach {sock curr_ip} $ip_list {
 set test ""
  catch {set test [gets $sock] }
   if {$test == "SERVER_OK" } { 
   set ret_ip $curr_ip
   puts "SUCCESS: Found server at: $curr_ip"
   break
   }
 }
 #close sockets again
 foreach {sock curr_ip} $ip_list {
 close $sock
 }
 }

 proc Configure_Server_Client {sock addr port} {
    global globals
    # Record the client's information
    fconfigure $sock -blocking 0 -buffering line
    # Set up a event if data is present at admin socket
    if {[catch {puts $sock "SERVER_OK"}]} {
    puts "remote gui socket not available anymore closing sock: $sock"
    close $sock
    return
    }
 ##for this check all is done I close the socket again
 close $sock
 puts "successfully etablished connection to client"
 exit
 }
 ###MAIN########
 if {$argc != 1} {
 puts "usage:[file tail $argv0] <server|client>"
 exit
 }
 set globals(client_server_port) 9901
 switch $argv {
        server {
                puts "opening server socket at port $globals(client_server_port)"
                socket -server Configure_Server_Client $globals(client_server_port)
                vwait forever
                }
        client {
                scan_ip 2 255
               }