基于c++ boost实现阻塞式ping指定IP
1.前言
在实际业务场景中,可能需要阻塞式检测目标IP连通性,本程序基于c++ boost库实现了一个简易的阻塞式ping指定IP例子。
2.原理
在循环中指定ping IP次数,通过标准输出判断有无"ttl"字段,如果字段的数目等于ping IP次数,那么就认为IP可达。
3.代码实例
3.1 ping.cpp
#include <iostream>
#include <string>
#include <signal.h>
#include <boost/process.hpp>
const std::string IP_ADDR("baidu.com");
const int PING_MAX_NUM = 4;
bool EXIT_ENABLE=false;
void sigintHandler(int signal)
{
EXIT_ENABLE = true;
}
int main()
{
signal(SIGINT, sigintHandler);
int status_count = 0;
while(status_count != PING_MAX_NUM) {
std::string cmd("ping -c " + std::to_string(PING_MAX_NUM) + " " + IP_ADDR);
boost::process::ipstream pipe_stream;
boost::process::child c(cmd, boost::process::std_out > pipe_stream);
std::string line;
while (pipe_stream && std::getline(pipe_stream, line) && !line.empty()) {
std::cerr << line << std::endl;
if (line.find("ttl") != std::string::npos) {
++status_count;
}
}
c.wait();
if (EXIT_ENABLE) {
break;
}
if (status_count != PING_MAX_NUM) {
status_count = 0;
usleep(1e6);
}
}
if (!EXIT_ENABLE) {
std::cout << "The network is normal." << std::endl;
} else {
std::cout << "Process exit." << std::endl;
}
return 0;
}
3.2 CMakeLists.txt
cmake_minimum_required(VERSION 3.0.2)
project(ping)
find_package(Boost REQUIRED COMPONENTS system)
add_executable(${PROJECT_NAME} ping.cpp)
target_link_libraries(${PROJECT_NAME} ${Boost_LIBRARIES})
4.运行结果
/home/test/code/ping/build/ping
PING baidu.com (110.242.68.66) 56(84) bytes of data.
64 bytes from 110.242.68.66 (110.242.68.66): icmp_seq=1 ttl=52 time=418 ms
64 bytes from 110.242.68.66 (110.242.68.66): icmp_seq=2 ttl=52 time=434 ms
64 bytes from 110.242.68.66 (110.242.68.66): icmp_seq=3 ttl=52 time=887 ms
64 bytes from 110.242.68.66 (110.242.68.66): icmp_seq=4 ttl=52 time=683 ms
The network is normal.
5.拓展
基于boost::process::child组件,可以根据实际需求运行不同的终端命令拿到终端的标准输出,比如将命令改为"ifconfig",
便可编程获取系统网卡信息。