How to ping a URL or a remote IP address using Node.js

avatar
Borislav Hadzhiev

Last updated: Apr 5, 2024
5 min

banner

# Table of Contents

  1. How to ping a URL or a remote IP address using Node.js
  2. Using the ping package to ping a remote server in Node.js

# How to ping a URL or a remote IP address using Node.js

To ping a URL or a remote IP address using Node.js:

  1. Use the child_process.exec() method to spawn a shell that executes a given command.
  2. Use the ping command from the underlying operating system to ping the remote server.
index.js
import child_process from 'child_process'; import util from 'util'; const exec = util.promisify(child_process.exec); async function ping(hostname) { try { const {stdout, stderr} = await exec(`ping -c 3 ${hostname}`); console.log('stderr: ', stderr); console.log('stdout: ', stdout); } catch (err) { console.log(err); } } ping('www.google.com');

ping remote url using node

The code for this article is available on GitHub

The code sample above uses the ES6 import/export syntax, however, you can also use the CommonJS require() syntax.

index.js
const child_process = require('child_process'); const util = require('util'); const exec = util.promisify(child_process.exec); async function ping(hostname) { try { const {stdout, stderr} = await exec(`ping -c 3 ${hostname}`); console.log('stderr: ', stderr); console.log('stdout: ', stdout); } catch (err) { console.log(err); } } ping('www.google.com');

ping remote url with node using common js

The code for this article is available on GitHub

Note that the examples use the ping command from the underlying system.

If you don't have ping installed, you can either install the module before you run the code snippet or use the approach from the next subheading.

The util.promisify() method takes a function that follows the common error-first callback style and returns a version that returns a Promise.

index.js
const exec = util.promisify(child_process.exec);

The child_process.exec() method spawns a shell and executes the given command within the shell, buffering any generated output.

index.js
const {stdout, stderr} = await exec(`ping -c 3 ${hostname}`);

The command string that you pass to the exec() function is processed directly by the shell, so special characters have to be escaped with a backslash \.

The command in the example pings the specified remote host 3 times but you can adjust this accordingly.

You can also omit the www. subdomain when issuing the command.

index.js
// ✅ Works const {stdout, stderr} = await exec('ping -c 3 google.com');

However, make sure you don't specify the protocol scheme (e.g. http:// or https://).

index.js
// ⛔️ Does NOT work const {stdout, stderr} = await exec('ping -c 3 https://google.com');

The code sample above produces the following error.

shell
Error: Command failed: ping -c 3 https://google.com ping: https://google.com: Name or service not known

# Using the ping package to ping a remote server in Node.js

You can also use the ping package to ping a remote server or an IP address in Node.js.

In case you don't have a package.json file, run the following command.

shell
npm init -y

Open your terminal in your project's root directory (where your pacakge.json file is) and run the following command to install ping.

shell
# with NPM npm install ping # or with YARN yarn add ping

npm install ping module

The code for this article is available on GitHub

Here is a simple example that pings 3 hosts.

index.js
import ping from 'ping'; // 👇️ Use this import if you use CommonJS require() // const ping = require('ping'); const hosts = ['192.168.1.1', 'google.com', 'yahoo.com']; async function example() { for (const host of hosts) { const response = await ping.promise.probe(host); console.log(response); } } example();

ping package with async await

The code for this article is available on GitHub

The ping.promise.probe() method takes a hostname or an IP address and a configurations object.

Here is an example that also passes the configurations object.

index.js
import ping from 'ping'; const hosts = ['192.168.1.1', 'google.com', 'yahoo.com']; async function example() { for (const host of hosts) { const config = { timeout: 10, // WARNING: -i 2 argument may not work in other platforms like windows extra: ['-i', '3'], }; const response = await ping.promise.probe(host, config); console.log(response); } } example();

The timeout configuration property is the timeout in seconds for each ping request.

Note that the -i 2 argument may not work on Windows.

The same approach can be used if you need to check if a single host is online.

index.js
import ping from 'ping'; async function example(host) { const config = { timeout: 10, // WARNING: -i 2 argument may not work in other platforms such as Windows extra: ['-i', '3'], }; const response = await ping.promise.probe(host, config); console.log(response); } example('google.com');

checking if single host is online ping package

The code for this article is available on GitHub

Here is an example that tests if multiple hosts are online using callbacks instead of async/await.

index.js
import ping from 'ping'; // 👇️ Use this import if you use CommonJS require() // const ping = require('ping'); const hosts = ['192.168.1.1', 'google.com', 'yahoo.com']; hosts.forEach(host => { ping.sys.probe(host, function (isAlive) { const message = isAlive ? 'host ' + host + ' is online' : 'host ' + host + ' is OFFLINE'; console.log(message); }); });

check if multiple hosts are online

The code sample checks if the 3 hosts in the URL are online or offline.

You can also pass a configuration object as the second argument to the ping.sys.probe() method.

index.js
import ping from 'ping'; // 👇️ Use this import if you use CommonJS require() // const ping = require('ping'); const hosts = ['192.168.1.1', 'google.com', 'yahoo.com']; const config = { timeout: 10, // WARNING: -i 2 may not work in other platforms like windows extra: ['-i', '3'], }; hosts.forEach(host => { ping.sys.probe( host, function (isAlive) { const message = isAlive ? 'host ' + host + ' is online' : 'host ' + host + ' is OFFLINE'; console.log(message); }, config, ); });
The code for this article is available on GitHub

We passed the following 3 arguments to the ping.sys.probe() method:

  1. The hostname or IP address to ping.
  2. A response callback function.
  3. Ping configuration object.

The callback function gets called with 3 arguments:

  1. isAlive - whether the ping request was successful.
  2. error - an error object or null if no error occurred.

The code sample above checks if 3 hosts are online, however, the same approach can be used to check if a single host is online.

index.js
import ping from 'ping'; // 👇️ Use this import if you use CommonJS require() // const ping = require('ping'); const config = { timeout: 10, // WARNING: -i 2 may not work in other platforms such as Windows extra: ['-i', '3'], }; const host = 'google.com'; ping.sys.probe( host, function (isAlive) { const message = isAlive ? 'host ' + host + ' is online' : 'host ' + host + ' is OFFLINE'; console.log(message); }, config, );

check if single host is online using callbacks syntax

The code for this article is available on GitHub

You can view more examples of using the ping module in the usage section of the package's NPM page.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.