Implementation method of C++ network connectivity detection
- 2020-05-30 20:51:33
- OfStack
Implementation method of C++ network connectivity detection
Sometimes the program needs to be connected to a specific network, so if someone is there, we can just look at it with the ping command.
The implementation idea is as follows:
Open the console with the program -
>
Run the ping command and specify that the console return value is written to the file -
>
Analyze the file and get the ping command to return the status -
>
Get the network connectivity
#include <windows.h>
#include <stdio.h>
#include <string>
using namespace std;
bool AnalysisFile()
{
bool rState;// Return status
FILE *file;
char ln[80];
fopen_s(&file, "returnpingdata.txt", "r");
fgets(ln, 80, file);// Read in the blank line, discard
fgets(ln, 80, file);// Read in ping Information, discard
fgets(ln, 80, file);// Read in ping Object returns a value for analysis
string data = ln;
int iPos = data.find("=");
data = data.substr(iPos+1,3);// Intercepting a string returns the number of bytes
int n = atoi(data.c_str());
rState = n > 0;
fclose(file);
return rState;
}
void main()
{
// -n 1 Specify the send 1 A data ,-w
// 1000 To specify more than 1000ms For the timeout
// >returnpingdata.txt Specifies the command line return value to be output to returnpingdata.txt In the file
char *cmdstr= "cmd /c ping www.baidu.com -n 1 -w 1000 >returnpingdata.txt";
WinExec(cmdstr, SW_HIDE);
Sleep(1000);// Waiting for the 1000ms
bool returndata = AnalysisFile();// Analyze the command line return file for network connection status
if (returndata==true)
{
printf(" Network connection successful \n");
}
else
{
printf(" Network connection failed \n");
}
getchar();
}
If you have any questions, please leave a message or come to the site community to exchange discussion, thank you for reading, hope to help you, thank you for your support of the site!