Skip to content

Instantly share code, notes, and snippets.

@mentix02
Created December 15, 2022 04:25
Show Gist options
  • Save mentix02/681a894deab532a0cd13f34db935c90c to your computer and use it in GitHub Desktop.
Save mentix02/681a894deab532a0cd13f34db935c90c to your computer and use it in GitHub Desktop.
Internet checker
#include <array>
#include <regex>
#include <chrono>
#include <thread>
#include <string>
#include <cstdio>
#include <memory>
#include <cstdint>
#include <iostream>
#include <stdexcept>
#define PING_CMD "nc -z fast.com 80"
std::string exec(const char* cmd) {
std::string result;
std::array<char, 128> buffer;
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose);
if (!pipe) {
throw std::runtime_error("popen() failed!");
}
while (std::fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
result += buffer.data();
}
return result;
}
int main() {
std::uint64_t counter = 1;
const std::regex pattern = std::regex{ "nor servname provided" };
std::cout << "attempt #" << counter << "... ";
while (std::regex_search(exec(PING_CMD), pattern)) {
std::cout << " fail\n";
std::this_thread::sleep_for(std::chrono::milliseconds(750));
counter += 1;
std::cout << "atempt #" << counter << "... ";
}
std::cout << "success\n";
return 0;
}
#!/usr/bin/env python3
import re
import time
import subprocess
PING_CMD = 'nc -z fast.com 80'
ERROR_MSG = re.compile("nor servname provided")
def main():
counter = 1
print(f'attempt #{counter}...', end=' ')
while ERROR_MSG.search(subprocess.getoutput(PING_CMD)):
print('failed')
time.sleep(0.75)
counter += 1
print(f'attempt #{counter}...', end=' ')
print('success')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment