Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To build an IPv4 ping command in Node.js, create an ICMP Echo Request (type 8, code 0), calculate its checksum, send it through a raw socket, and accept only a matching Echo Reply (type 0, code 0). Node’s Buffer methods handle the packet’s bytes; a raw-socket module provides access to ICMP, but operating-system permissions and native build requirements can make an OS ping subprocess easier to deploy.

What an IPv4 ping packet contains

Ping uses ICMP Echo messages. RFC 792 defines an Echo Request as type 8, code 0 and an Echo Reply as type 0, code 0. The reply carries back the request’s identifier and sequence number so the sender can associate it with the right probe.

Byte offset Length Field Echo Request value
0 1 byte Type 8
1 1 byte Code 0
2–3 2 bytes Checksum Calculated over the complete ICMP message
4–5 2 bytes Identifier Chosen by the sender
6–7 2 bytes Sequence number Chosen by the sender
8 onward Variable Payload Opaque data, such as a timestamp or marker

The 16-bit fields use network byte order, also called big-endian. The checksum is the 16-bit one’s complement of the one’s-complement sum of the ICMP message, beginning with the Type field. Set the checksum bytes to zero while calculating it. If the message has an odd number of bytes, treat the final byte as the high byte of a word whose low byte is zero. These rules are specified in IETF RFC 792 (1981).

Build the packet and calculate its checksum

Node’s Buffer API makes each field’s width and byte order explicit: write Type and Code with writeUInt8, and Identifier and Sequence with writeUInt16BE. The methods check buffer bounds and require unsigned values within the supported range for the chosen field width; a 16-bit field must be between 0 and 65535.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
CanaKit Raspberry Pi 5 Starter Kit PRO - Turbine Black (128GB Edition) (8GB RAM)
  • Includes Raspberry Pi 5 with 2.4Ghz 64-bit quad-core CPU (8GB RAM)
  • Includes 128GB Micro SD Card pre-loaded with 64-bit Raspberry Pi OS, USB MicroSD Card Reader
  • CanaKit Turbine Black Case for the Raspberry Pi 5
  • CanaKit Low Noise Bearing System Fan
  • Mega Heat Sink - Black Anodized
function checksum(buf) {
  let sum = 0;
  for (let i = 0; i < buf.length; i += 2) {
    const hi = buf[i];
    const lo = i + 1 < buf.length ? buf[i + 1] : 0;
    sum += (hi << 8) | lo;
    while (sum > 0xffff) sum = (sum & 0xffff) + (sum >>> 16);
  }
  return (~sum) & 0xffff;
}

function makeEchoRequest(identifier, sequence, payload) {
  const headerLength = 8;
  const packet = Buffer.alloc(headerLength + payload.length);

  packet.writeUInt8(8, 0);                 // Echo Request type
  packet.writeUInt8(0, 1);                 // Code
  packet.writeUInt16BE(0, 2);              // Zero during checksum calculation
  packet.writeUInt16BE(identifier, 4);
  packet.writeUInt16BE(sequence, 6);
  payload.copy(packet, headerLength);
  packet.writeUInt16BE(checksum(packet), 2);
  return packet;
}

const payload = Buffer.from('node-ping', 'ascii');
const request = makeEchoRequest(0x1234, 1, payload);

Buffer.alloc() initializes the bytes, so the checksum field begins at zero; it is also explicitly written as zero before the calculation. The checksum function adds adjacent bytes as big-endian 16-bit words, folds any carry back into the low 16 bits, pads an odd final byte for calculation, then complements the result. The checksum is written at offset 2 only after the whole message—including its payload—is assembled.

Send and match an Echo Reply

The raw-socket npm package exposes raw sockets to Node and sends and receives data as Buffer objects. Its native C++ component can require a working node-gyp build toolchain during installation. Once installed, a basic socket setup follows this shape:

Rank #2
CanaKit Raspberry Pi 4 4GB Starter PRO Kit - 4GB RAM
  • Includes Raspberry Pi 4 4GB Model B with 1.5GHz 64-bit quad-core CPU (4GB RAM)
  • Includes Pre-Loaded 32GB EVO+ Micro SD Card (Class 10), USB MicroSD Card Reader
  • CanaKit Premium High-Gloss Raspberry Pi 4 Case with Integrated Fan Mount, CanaKit Low Noise Bearing System Fan
  • CanaKit 3.5A USB-C Raspberry Pi 4 Power Supply (US Plug) with Noise Filter, Set of Heat Sinks, Display Cable - 6 foot (Supports up to 4K60p)
  • CanaKit USB-C PiSwitch (On/Off Power Switch for Raspberry Pi 4)
const raw = require('raw-socket');

const socket = raw.createSocket({ protocol: raw.Protocol.ICMP });
socket.on('message', (buffer, source) => {
  // Parse and validate a response before treating it as a successful ping.
});

socket.send(request, 0, request.length, destination, (error, bytes) => {
  if (error) {
    // Handle send failure.
  }
});

The package’s documented model uses a message callback for received buffers and a send callback for errors and the number of bytes sent. The exact receive-buffer layout can depend on the operating system and raw-socket behavior: confirm whether the callback buffer begins at the ICMP header or includes an IPv4 header, and use the correct ICMP offset before parsing. Do not interpret an IP header as an ICMP Type byte.

For a buffer that begins at the ICMP header, validate the response like this:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
ELECROW CrowPi Case Kit for Raspberry Pi 5, 9-Inch Display
  • Not including the Raspberry Pi 5 (8GB), the Crowpi advanced version comes with the Raspberry Pi 5
  • ELECROW Black Case for the Raspberry Pi 5, CrowPi is equipped with a 9-inch HD touchscreen along with a camera; All the regular components used in DIY electronics are packed into the CrowPi development board, such as LCD, LED matrix, buzzer, light sensor, PIR sensor, ultrasonic sensor, IR sensor, etc
  • Raspberry Pi Sensors: The Crowpi raspberry pi 5 programming kit is jam-packed with lots of buttons such as 19 different sensors in a tidy easy to use package; You don't have to wait and wire things
  • Build Quality: Solid ABS shell and well made components in one place make it strong and convenient to travel
  • Programming Lessons: This raspberry pi 5 learning kit ships with step by step instructions and provides 21 lessons to take you through identifying components reading code and running it in the terminal
function isMatchingEchoReply(packet, identifier, sequence) {
  if (packet.length < 8) return false;
  return packet.readUInt8(0) === 0 &&
    packet.readUInt8(1) === 0 &&
    packet.readUInt16BE(4) === identifier &&
    packet.readUInt16BE(6) === sequence;
}

A production implementation should associate pending probes with both identifier and sequence number, rather than treating any received ICMP packet as a reply. Start a monotonic timer immediately before sending; when a matching reply arrives, compute elapsed time from that timer and report the round-trip duration. Ignore packets with the wrong type, code, identifier, or sequence. Other ICMP traffic can reach a raw socket, and a destination may return an error message rather than an Echo Reply.

Timeouts and socket cleanup

For each pending probe, start a timeout that removes its identifier-and-sequence entry and reports a timeout if no valid reply arrives. With one probe, close the socket when the request completes or times out. With multiple probes, keep the socket open and remove only the expired request; close the shared socket when the ping operation is finished. Clear the timer when a matching reply arrives so a late timeout cannot report the same probe twice.

Rank #4
CanaKit Raspberry Pi 5 Desktop PC with SSD (Fully Assembled) (256 GB SSD)
  • Fully assembled for plug-and-play operation
  • Includes Raspberry Pi 5 with 8GB RAM
  • 256 GB PCIe Pi NVMe SSD (Pre-loaded with Pi 64-Bit OS)
  • M.2 HAT+
  • CanaKit Turbine Black Case for the Pi 5

Choose raw ICMP, an OS command, or a higher-level library

The right approach depends on whether you need to control packet bytes or simply check reachability. A third-party ping library may simplify the interface, but its platform behavior and implementation details depend on the specific package.

Approach Packet control Portability and permissions Build and parsing burden
Raw ICMP through a native module High: construct and inspect ICMP messages directly Depends on OS raw-socket support and policy; elevated privileges may be required Native build toolchain may be needed; application must build packets, match replies, handle timeouts, and account for receive-buffer layout
Operating-system ping subprocess Low: the OS controls packet details Uses the host’s installed utility and its platform-specific options No raw-socket parsing in the Node program; output and command flags vary by platform
Higher-level third-party ping library Varies by package Varies by package and operating system Can provide a simpler API; verify whether it uses raw sockets or an OS subprocess and check its installation and platform requirements

Raw ICMP is useful when the purpose is to learn packet layout, buffers, network byte order, and one’s-complement arithmetic. If the goal is only to check whether a host responds, invoking the operating system’s own ping utility often avoids implementing packet parsing and raw-socket handling.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
RasTech Raspberry Pi 5 8GB Kit with Active Cooler and Pi5 Case
  • 【What you Get】You will get 1*Pi 5 8GB Single Board,1*RasTech Case,1*Active Cooler,1*Screwdriver,1*Installation instructions,12-month free warranty, lifetime service, 24-hour prompt and friendly response.
  • 【More Connectors】There are two USB 3.0 ports(5Gbps simultaneously) and two USB 2.0 ports, which triple total bandwidth ,support any combination of up to two cameras or displays. Peak SD card performance is doubled through support for the SDR104 high-speed mode. It provides a smooth desktop experience for you. Offer Gigabit Ethernet and a PCIe interface, along with dual-band Wi-Fi and Bluetooth 5.0/BLE wireless capability. The RasTech Pi 5 Kit use the new 27W 5.1V 5A USB-C power connector.
  • 【 Support Dual 4Kp60 Display 】Each of the two microHDMI sockets can control a 4K display at 60 Hertz, now support HDR, offering super HD video for media streaming projects. RPi 5 is the first RPi model that comes with a PCI Express port (PCIe 2.0 x1 with 500 MB/s) to attach SSDs (requires separate M.2 HAT).
  • 【 Excellent Chips And Applications】Pi 5 is a full-size Pi computer using silicon built in-house at Pi. The RP1 “southbridge” provides the bulk of the I/O capabilities for Pi 5. Pi 5 is more friendly and convenient in the development of Internet of Things, Web development, machine identification, automatic control and other electronic equipment applications and network.
  • 【 Faster CPU, Better GPU 】 Pi 5 features a Broadcom BCM2712 64-bit quad-core Arm Cortex-A76 processor running at 2.4GHz, it delivers a 2–3× increase in CPU performance relative to RaspberryPi 4. The 800MHz VideoCore VII GPU is compatible to OpenGL ES 3.1 and Vulkan 1.2, substantial uplift in graphics performance. Pi 5 Offers lightning-fast CPU speed, a PCI Express interface, a Real Time Clock (RTC) and a power button and runs significantly cooler than Pi 4.

Use an OS ping command when packet control is unnecessary

Use Node’s child_process.execFile rather than constructing a shell command string from user input. The flags differ: common forms use -c to set the probe count on Unix-like systems and -n on Windows. Validate the destination, choose flags for the actual operating system, and set an execution timeout. The utility’s exit code and output format are operating-system dependent, so interpret them accordingly.

const { execFile } = require('node:child_process');
const { platform } = require('node:os');

function pingOnce(host, callback) {
  const windows = platform() === 'win32';
  const args = windows ? ['-n', '1', host] : ['-c', '1', host];
  execFile('ping', args, { timeout: 5000 }, callback);
}

This example chooses one probe and a five-second process timeout; it does not make the output format identical across systems. In an application, validate or constrain host and handle missing utilities, permission or policy errors, process timeouts, and nonzero exit codes.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common failures and what they mean

  • Raw socket creation is denied: the operating system may require elevated privileges or disallow the requested socket mode. Treat this as an environment limitation, not a checksum bug; use the OS ping utility where raw sockets are unavailable.
  • Package installation fails: the native module may not compile because the required C++ compiler or node-gyp toolchain is absent or incompatible with the environment.
  • No Echo Reply arrives: the destination may be unreachable, ICMP may be filtered, or the request may time out. A timeout alone does not establish that the host is down.
  • An unexpected ICMP packet arrives: raw sockets can receive traffic other than the Echo Reply being awaited. Check the ICMP type and code, then match the identifier and sequence before resolving a probe.
  • Name lookup fails: resolve a hostname before sending, report DNS failures separately from ICMP timeouts, and use the resolved address consistently for that probe.
  • Parsing appears shifted: check whether the receive callback includes an IPv4 header. Apply the correct header offset before reading ICMP fields, and reject buffers too short to contain the fields being accessed.

IPv6 needs a separate implementation

This packet format and checksum code describe IPv4 ICMP Echo messages; they are not a portable IPv6 ping implementation. ICMPv6 has different checksum handling, including dependence on the IPv6 pseudo-header in relevant raw-socket use. RFC 2292 discusses ICMPv6 raw-socket behavior, but an IPv4 packet must not simply be reused as an IPv6 packet. Use an IPv6-aware implementation and verify the operating system’s raw-socket requirements for it.

Quick Recap

Bestseller No. 1
CanaKit Raspberry Pi 5 Starter Kit PRO - Turbine Black (128GB Edition) (8GB RAM)
CanaKit Raspberry Pi 5 Starter Kit PRO - Turbine Black (128GB Edition) (8GB RAM)
Includes Raspberry Pi 5 with 2.4Ghz 64-bit quad-core CPU (8GB RAM); CanaKit Turbine Black Case for the Raspberry Pi 5
$259.95
Bestseller No. 2
CanaKit Raspberry Pi 4 4GB Starter PRO Kit - 4GB RAM
CanaKit Raspberry Pi 4 4GB Starter PRO Kit - 4GB RAM
Includes Raspberry Pi 4 4GB Model B with 1.5GHz 64-bit quad-core CPU (4GB RAM); Includes Pre-Loaded 32GB EVO+ Micro SD Card (Class 10), USB MicroSD Card Reader
$159.99
Bestseller No. 4
CanaKit Raspberry Pi 5 Desktop PC with SSD (Fully Assembled) (256 GB SSD)
CanaKit Raspberry Pi 5 Desktop PC with SSD (Fully Assembled) (256 GB SSD)
Fully assembled for plug-and-play operation; Includes Raspberry Pi 5 with 8GB RAM; 256 GB PCIe Pi NVMe SSD (Pre-loaded with Pi 64-Bit OS)
$339.97

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.