Skip to content

Instantly share code, notes, and snippets.

@skeptomai
Created February 5, 2009 07:07
Show Gist options
  • Save skeptomai/58588 to your computer and use it in GitHub Desktop.
Save skeptomai/58588 to your computer and use it in GitHub Desktop.
require 'socket'
include Socket::Constants
def can_connect?(addr, port, timeout=2)
t = Socket.new(AF_INET, SOCK_STREAM, 0)
saddr = Socket.pack_sockaddr_in(port, addr)
connected = false
begin
t.connect_nonblock(saddr)
rescue Errno::EINPROGRESS
IO::select(nil,[t],nil,timeout)
begin
t.connect_nonblock(saddr)
rescue Errno::EISCONN
t.close
connected = true
rescue SystemCallError
end
rescue SystemCallError
end
connected
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment