Pinging a Machine

Table of contents:


You want to check whether a particular machine or domain name can be reached from your computer.


Use Rubys standard ping library. Its single method, Ping.pingecho, TRies to get some machine on the network to respond to its entreaties. It takes either a domain name or an IP address, and returns true if it gets a response.

	require ping

ping.pingecho( 	 # => true

	# timeout of 10 seconds instead of the default 5 seconds
	Ping.pingecho(, 10) # => true
ping port 80 instead of the default echo port
Ping.pingecho(, 5, 80) # => true

o.such.domain) # => false
Ping.pingecho( # => false


Ping.pingecho performs a TCP echo: it tries to make a TCP connection to the given machine, and if the machine responds (even if to refuse the connection) it means the machine was reachable.

This is not the ICMP echo of the Unix ping command, but the difference almost never matters. If you absolutely need an ICMP echo, you can invoke ping with a system call and check the return value:

	system(ping -c1
	# 64 bytes from icmp_seq=0 ttl=42 time=27.2 ms
	# --- ping statistics --
	# 1 packets transmitted, 1 packets received, 0% packet loss
	# round-trip min/avg/max = 27.2/27.2/27.2 ms
	# => true

If the domain has a DNS entry but can be reached, Ping::pingecho may raise a Timeout::Error instead of returning false.

Some very popular or very paranoid domains, such as, don respond to incoming ping requests. However, you can usually access the web server or some other service on the domain. You can see whether such a domain is reachable by using one of Rubys other libraries:

	ping.pingecho( # => false

	Net::HTTP.start( { success! } # => "success!"
o.such.domain) { "success!" }
	# SocketError: getaddrinfo: Name or service not known



Date and Time



Files and Directories

Code Blocks and Iteration

Objects and Classes8

Modules and Namespaces

Reflection and Metaprogramming


Graphics and Other File Formats

Databases and Persistence

Internet Services

Web Development Ruby on Rails

Web Services and Distributed Programming

Testing, Debugging, Optimizing, and Documenting

Packaging and Distributing Software

Automating Tasks with Rake

Multitasking and Multithreading

User Interface

Extending Ruby with Other Languages

System Administration

Ruby Cookbook
Ruby Cookbook (Cookbooks (OReilly))
ISBN: 0596523696
EAN: 2147483647
Year: N/A
Pages: 399 © 2008-2020.
If you may any questions please contact us: