Script to ping computer

Shelling out for this makes me feel very icky, especially when Java already has the native ability to do this and that’s an invitation to accidentally send horrible things to the command line. Why not just:

def ping(address,timeout=2000):
	from java.net import InetAddress
	ip = InetAddress.getByName(address)
	return ip.isReachable(timeout)

This will throw UnknownHostException if the host can’t be looked up, or IOException if the network is broken, so you can handle that case as well, instead of not even knowing it happened unless you parse unexpected command-line output. Or just swallow exceptions, of course.

java.net.* can do all the fun things you thought you needed command-line tools for, and more.

22 Likes