基于c++ boost实现阻塞式ping指定IP

本文档介绍了一个使用C++ Boost库创建的阻塞式ping程序,用于检测目标IP的连通性。程序通过监听"ttl"字段来判断IP是否可达,并在接收到中断信号时优雅退出。示例代码展示了如何利用boost::process组件执行ping命令并捕获输出,同时提供了CMakeLists.txt文件以供构建项目。
摘要由CSDN通过智能技术生成

基于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",
便可编程获取系统网卡信息。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值