Skip to content

Instantly share code, notes, and snippets.

@olivatooo
Last active May 7, 2020 20:09
Show Gist options
  • Save olivatooo/e1cbc60629c98d054d5503674a2a8327 to your computer and use it in GitHub Desktop.
Save olivatooo/e1cbc60629c98d054d5503674a2a8327 to your computer and use it in GitHub Desktop.
A simple portable C++ ping using popen
// C++ Libraries
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
template <typename TP> std::string Num2Str(TP const& value ){
std::stringstream sin;
sin << value;
return sin.str();
}
bool Ping( const std::string& address, const int& max_attempts )
{
// Format a command string
// Maybe need to sanitize command?
#ifdef _WIN32
std::string command = "ping -n " + Num2Str(max_attempts) + " " + address;
#else
std::string command = "ping -c " + Num2Str(max_attempts) + " " + address;
#endif
std::stringstream sout;
FILE *in;
char buff[512];
// Open ping read-only
#ifdef _WIN32
if(!(in = _popen(command.c_str(), "r"))){
#else
if(!(in = popen(command.c_str(), "r"))){
#endif
return true;
}
// Get output
while(fgets(buff, sizeof(buff), in) != nullptr){
sout << buff;
}
// Close
int exit_code = pclose(in);
return exit_code;
}
int main( int argc, char* argv[] )
{
std::string host = "www.google.com";
int max_attempts = 3;
// Execute the command
bool result = Ping( host, max_attempts);
std::cout << host << " ";
if(!result){
std::cout << " is responding." << std::endl;
}
else{
std::cout << " is not responding.";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment