简体   繁体   English

如何在 c++ 程序中 ping 某个 ip

[英]how to ping a certain ip in a c++ program

Usually I just use the system("ping 8.8.8.8");通常我只是使用system("ping 8.8.8.8"); command, but I am trying to store information in a variable (IP) and then ping that IP using system in a c++ program.命令,但我试图将信息存储在变量(IP)中,然后在 c++ 程序中使用系统 ping IP。

This seems very easy, but when I tried to execute the code, it tells me there are too many arguments in function call.这看起来很简单,但是当我尝试执行代码时,它告诉我 function 调用中有太多 arguments 。 Can anybody please help me with a solution to this?有人可以帮我解决这个问题吗?

ImGui::PushItemWidth(100);
static char IP[64] = ""; ImGui::InputText("PING IP", IP, 64);
ImGui::PopItemWidth();

if (ImGui::Button("ping test")) {
    system("ping ", IP);
}

The system() function takes exactly one argument, as defined by its header file: system() function 只采用一个参数,由其 header 文件定义:

int system( const char* command );

It expects a full command string to be executed by the shell.它期望 shell 执行完整的命令字符串。

The easiest way to handle this case will be to concatenate the "ping" string literal and the IP variable.处理这种情况的最简单方法是将"ping"字符串文字和IP变量连接起来。 You can do it using std::string instead of char arrays pretty easily in C++:您可以在 C++ 中使用std::string而不是 char arrays 很容易地做到这一点:

#include <iostream>
#include <string>
#include <cstdlib>

int main() {
    std::string IP ("127.0.0.1");
    std::string CMD ("ping " + IP);
    std::system(CMD.c_str());
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM