Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to check if socket port is open?

Status
Not open for further replies.

fgiovanni

Programmer
Oct 3, 2002
5
US
Is there a way to determine if a particular socket port is free?

I would like to open a socket to a particular port number.

However, if it is not free the 'socket' command will cause a Tcl/Tk error and exit.
 
A way to achieve your goal is to use the 'catch' command.
This command catches the error and gives you a return-code and a string indicating the result of the command:

set rc [catch {socket $host $port} msg}
if {$rc == 0} {
# all is ok and msg holds the result of the command
set channel $msg
} else {
# some error occured and msg holds the error message
log "can't open port $port on $host\nreason: $msg"
}

Excerpt of the Tcl manual:
The catch command may be used to prevent errors from aborting command interpretation. Catch calls the Tcl interpreter recursively to execute script, and always returns without raising an error, regardless of any errors that might occur while executing script.

If script raises an error, catch will return a non-zero integer value corresponding to one of the exceptional return codes (see tcl.h for the definitions of code values). If the varName argument is given, then the variable it names is set to the error message from interpreting script.

If script does not raise an error, catch will return 0 (TCL_OK) and set the variable to the value returned from script.


HTH

ulis
 
There's no way to test the availability of a port from Tcl. However, you can simply catch the call to socket, and if catch indicates that an error occurred (by returning a non-zero value), handle the error accordingly:

Code:
if {[catch {socket -server Connect 9001} sid]} {
  # We encountered an error
  puts stderr "Couldn't start server: $sid"
}
- Ken Jones, President, ken@avia-training.com
Avia Training and Consulting, 866-TCL-HELP (866-825-4357) US Toll free
415-643-8692 Voice
415-643-8697 Fax
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top