Skip to content

Instantly share code, notes, and snippets.

@hmarr
Last active November 6, 2019 14:04
Show Gist options
  • Save hmarr/2f58da0884f9caf8c7e64d2a0505a3a4 to your computer and use it in GitHub Desktop.
Save hmarr/2f58da0884f9caf8c7e64d2a0505a3a4 to your computer and use it in GitHub Desktop.
TCP ping in Ruby
#!/usr/bin/env ruby
require "socket"
require "timeout"
if ARGV.length < 2
puts "usage: tcping HOST PORT"
exit 1
end
host = ARGV[0]
port = ARGV[1].to_i
loop do
start = Time.now
status = "OK"
begin
Timeout.timeout(1) { TCPSocket.new(host, port) }
rescue Timeout::Error
status = "Timeout"
rescue Errno::ECONNREFUSED
status = "Connection refused"
end
time_ms = ((Time.now - start) * 1000).to_i
puts "#{status} % 4d ms" % time_ms
sleep 0.5
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment