Ruby Checking to see if website exists -
ok checking see if server running. works long port correct. if cange port 1 know not excepted skips if routine. example below works fine. change port number 99 , skips if. think should fall else section.
url = uri.parse("http://www.google.com/") url.port = 80 req = net::http.new(url.host, url.port) res = req.request_head(url.path) if res.code == "200" #do else #do else end
you should provide timeout , rescue socketerror
, timeout::error
:
require "net/http" def check_server(server, port) begin http = net::http.start(server, port, {open_timeout: 5, read_timeout: 5}) begin response = http.head("/") if response.code == "200" # fine else # unexpected status code end rescue timeout::error # timeout reading server end rescue timeout::error # timeout connecting server rescue socketerror # unknown server end end
if want check if server up, can simplified:
require "net/http" def up?(server, port) http = net::http.start(server, port, {open_timeout: 5, read_timeout: 5}) response = http.head("/") response.code == "200" rescue timeout::error, socketerror false end
it returns true
if /
returns 200
status code , false
otherwise, i.e. other status codes, timeouts , typical error conditions.
Comments
Post a Comment