DataReelDataReelC++ Transition Guide

Examples › Socket Examples

socket_ping

C++20 or laterC++ standard library onlyPOSIX (Linux, UNIX)

Legacy: examples_socket/ping/testprog.cpp · Modern: examples_modern/socket/ping/modern.cpp

Modern equivalent of the ping example. The legacy program opens a raw ICMP socket, which needs root or a setuid binary. Linux (and macOS) also offer unprivileged ICMP "ping sockets" (SOCK_DGRAM with IPPROTO_ICMP, allowed by net.ipv4.ping_group_range), so this program needs no privileges. The echo request is a std::array of bytes, the round trip is timed with std::chrono::steady_clock, the socket is closed by an RAII guard, and poll() waits with a timeout. If ping sockets are not allowed on the host the program says so and exits 0.

Usage: modern [IPv4 address] (default 127.0.0.1)

Legacy calls in this program

LegacyModern C++StandardNotes
gxSocketkeep gxSocket (C++ has no sockets); servers in std::jthread with std::stop_token and select() timeoutsC++20Stopping is a request, not a canceled thread blocked in accept().
gxsPing (raw socket, root)unprivileged ICMP socket (SOCK_DGRAM, IPPROTO_ICMP) on LinuxPOSIX

From the transition tables.

Side by side

DataReel 6.4 (legacy)

examples_socket/ping/testprog.cpp 76 lines
#include "gxdlcode.h"

#if defined (__USE_ANSI_CPP__) // Use the ANSI Standard C++ library
#include <iostream>
using namespace std; // Use unqualified names for Standard C++ library
#else // Use the old iostream library by default
#include <iostream.h>
#endif // __USE_ANSI_CPP__

#include "gxsping.h"

#ifdef __MSVC_DEBUG__
#include "leaktest.h"
#endif

int main(int argc, char **argv)
{
#ifdef __MSVC_DEBUG__
  InitLeakTest();
#endif

#ifdef __UNIX__
  // Raw sockets require root access on all UNIX platforms. Programs
  // that use raw sockets can be excucuted by non-root users if the
  // effective user ID of the executing process is set to the same as
  // the file's owner. In the case root must own the executable and
  // the effective User-ID or Group-ID on execution bit must be set
  // by root using the chmod command: "chmod u+s" or "chmod 4755"
  // Now the effective user ID of the executing process will be set to 
  // the same user ID of the file's owner. 
  if(geteuid() != 0) {
    cout << "You must be root to run this program" << "\n";
    return 1;
  }
#endif

  // Check the command line arguments
  if(argc != 2) {
    cout << "\n";
    cout << "Usage: " << argv[0] << " hostname" << "\n";
    return 1;
  }

  char *hostname = argv[1];
  
  // Construct a raw socket
  gxSocket raw_socket(AF_INET, SOCK_RAW, IPPROTO_ICMP, 0, hostname);
  if(!raw_socket) {
    cout << raw_socket.SocketExceptionMessage() << "\n";
    return 1;
  }
  
  char ip_address[gxsMAX_NAME_LEN];
  raw_socket.GetBoundIPAddress(ip_address);
  cout << "Pinging " << ip_address << " with " << gxsECHO_REQ_DATASIZE
       << " bytes of data..." << "\n";

  gxsPing ping(&raw_socket);
  
  // Ping with a timeout value of one second
  if(ping.Ping(1) != gxSOCKET_NO_ERROR) {
    cout << ip_address << " is not responding" << "\n";
    cout << raw_socket.SocketExceptionMessage() << "\n";
    return 1;
  }

  cout << "Reply from " << ip_address << ": bytes=" << gxsECHO_REQ_DATASIZE
       << " time=" << ping.elapsed_time << "ms"
       << " TTL=" << ping.time_to_live << "\n";

  return 0;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Modern C++ (C++20)

examples_modern/socket/ping/modern.cpp 62 lines
#include <arpa/inet.h>
#include <array>
#include <cerrno>
#include <chrono>
#include <cstdint>
#include <cstring>
#include <iostream>
#include <netinet/ip_icmp.h>
#include <poll.h>
#include <string>
#include <sys/socket.h>
#include <unistd.h>

struct Fd {                                    // RAII for a descriptor
  int fd;
  ~Fd() { if(fd >= 0) close(fd); }
};

int main(int argc, char **argv)
{
  const std::string host = argc > 1 ? argv[1] : "127.0.0.1";
  sockaddr_in to{};
  to.sin_family = AF_INET;
  if(inet_pton(AF_INET, host.c_str(), &to.sin_addr) != 1) {
    std::cout << "Not an IPv4 address: " << host << "\n";
    return 1;
  }
  Fd s{socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP)};
  if(s.fd < 0) {
    std::cout << "ICMP ping sockets are not allowed here (" << std::strerror(errno)
              << "); skipped\n";
    return 0;
  }

  std::array<unsigned char, 8 + 32> packet{};  // ICMP header + 32 data bytes
  packet[0] = ICMP_ECHO;                       // Type 8, code 0
  for(std::size_t i = 8; i < packet.size(); i++) packet[i] = static_cast<unsigned char>(i);
  // The kernel fills in the identifier and checksum for ping sockets

  for(int seq = 1; seq <= 3; seq++) {
    packet[6] = 0; packet[7] = static_cast<unsigned char>(seq);
    auto start = std::chrono::steady_clock::now();
    if(sendto(s.fd, packet.data(), packet.size(), 0,
              reinterpret_cast<sockaddr *>(&to), sizeof to) < 0) {
      std::cout << "sendto: " << std::strerror(errno) << "\n";
      return 1;
    }
    pollfd p{s.fd, POLLIN, 0};
    if(poll(&p, 1, 1000) <= 0) { std::cout << "Request timed out\n"; continue; }
    std::array<unsigned char, 1500> reply{};
    ssize_t n = recv(s.fd, reply.data(), reply.size(), 0);
    auto rtt = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - start);
    if(n >= 8 && reply[0] == ICMP_ECHOREPLY)
      std::cout << "Reply from " << host << ": bytes=" << n - 8 << " seq=" << seq
                << " time=" << rtt.count() << " ms\n";
  }
  return 0;
}
// ----------------------------------------------------------- // 
// ------------------------------- //
// --------- End of File --------- //
// ------------------------------- //

Build and run

cmake -S examples_modern -B build-modern -DCMAKE_CXX_STANDARD=20
cmake --build build-modern --target socket_ping
./build-modern/socket_ping
# or without CMake:
g++ -std=c++20 -pthread -o socket_ping examples_modern/socket/ping/modern.cpp

Output of the modern program

From run_modern_tests.sh on RHEL 10, GCC 14, C++20.

Reply from 127.0.0.1: bytes=32 seq=1 time=0.040367 ms
Reply from 127.0.0.1: bytes=32 seq=2 time=0.007226 ms
Reply from 127.0.0.1: bytes=32 seq=3 time=0.005837 ms