gpt-3.5-turbo-0613· OpenAI
WildChat-4.8M (AI2)
ubuntu20 c++中,如何ping www.baidu.com判断当前网络是否通畅
- User
ubuntu20 c++中,如何ping www.baidu.com判断当前网络是否通畅
- Assistant
在Ubuntu 20的C++程序中,你可以使用系统调用或者开源的网络库去执行ping命令并判断网络是否通畅。下面是两种方法的示例:
- 使用系统调用执行ping命令:
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { // 执行ping命令 char command[] = "ping -c 1 www.baidu.com"; FILE* pingResult = popen(command, "r"); if (pingResult != NULL) { char response[256] = ""; while (fgets(response, sizeof(response), pingResult) != NULL) { // 判断ping命令的输出中是否包含 "1 packets transmitted, 1 received",表示网络通畅 if (strstr(response, " 1 packets transmitted, 1 received") != NULL || strstr(response, " 1 packets transmitted, 1 received, 0% packet loss") != NULL) { printf("网络通畅\n"); } } pclose(pingResult); } else { printf("执行ping命令失败\n"); } return 0; }