On Wed, Jan 30, 2013 at 3:54 PM, Mamba Black <[email protected]> wrote:
> Hi,
>   Please correct if my understanding is wrong for the below code:-
> Code to check if a port is free or not.
>
> def port_available?(port)
>   begin
>     TCPServer.new('localhost', port).close
>     rescue
>       return false
>     else
>      return true
>   end
> end

I personally prefer to put the "true" before the "rescue" because this
is the regular control flow.  You can even change that to a one liner

def port_alive? port
  (TCPServer.new('localhost', port).close; true) rescue false
end

> Port will be closed. While closing if an exception occurs, it
> returns false. Else true.

But note that your system may have multiple network addresses and this
check verifies just one.  The same port could be occupied on another
address.

Plus, if you do the check to decide whether to start a server on that
port the port may be closed the very moment you try to open the port
"for real".  In these situations it's usually better to just open the
port and deal with the error because you need to do that anyway.

Kind regards

robert

-- 
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/

-- 
[email protected] | 
https://groups.google.com/d/forum/ruby-talk-google?hl=en
--- 
You received this message because you are subscribed to the Google Groups 
"ruby-talk-google" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to