#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <string>
#include <vector>
#include <unistd.h>
using namespace std;
bool checkNet()
{
/*
-c 2(代表ping次数,ping 2次后结束ping操作) -w 2(代表超时时间,2秒后结束ping操作)
*/
// system("ping www.google.com -c 2 -w 2 >netlog.bat");
system("ping www.baidu.com -c 2 -w 2 >netlog.bat");
sleep(2);
//把文件一行一行读取放入vector
ifstream infile;
infile.open("netlog.bat");
string s;
vector<string> v;
while(infile)
{
getline(infile,s);
if(infile.fail())
break;
v.push_back(s);
}
infile.close();
//读取倒数第二行 2 packets transmitted, 2 received, 0% packet loss, time 1001ms
if (v.size() > 1)
{
string data = v[v.size()-2];
int iPos = data.find("received,");
if (iPos != -1 )
{
data = data.substr(iPos+10,3);//截取字符串返回packet loss
int n = atoi(data.c_str());
if(n == 0)
return 1;
else
return 0 ;
}
}else{
return 0;
}
}
int main()
{
//分析命令行返回文件,得到网络连接情况
if (checkNet())
{
printf("网络连接成功\n");
}
else
{
printf("网络连接失败\n");
}
}