【求教】怎么用c语言来判断网络是否通
比如 用ping 192.168.1.12 让c语言判断 是通还是不通怎么来实现 c 网络
[解决办法]
仅供参考
#include <windows.h>
#include <stdio.h>
char cmdstr[256];
int i;
int YN(int k) {
FILE *f;
char fn[40];
char ln[80];
int yn=0;
sprintf(fn,"d:\\ping%d.txt",k);
f=fopen(fn,"r");
if (NULL!=f) {
fgets(ln,80,f);
fgets(ln,80,f);
fgets(ln,80,f);
if (1==fscanf(f,"Re%c",&yn)) yn='q'-yn;
fclose(f);
unlink(fn);
}
return yn;
}
void main() {
for (i=115;i<130;i++) {
sprintf(cmdstr,"cmd /c ping 192.168.2.%d -n 1 -w 1000 >d:\\ping%d.txt",i,i);
WinExec(cmdstr,SW_HIDE);
}
Sleep(3000);
for (i=115;i<130;i++) {
printf("%d 192.168.2.%d\n",YN(i),i);
}
}
//1 192.168.2.115
//0 192.168.2.116
//0 192.168.2.117
//0 192.168.2.118
//1 192.168.2.119
//0 192.168.2.120
//0 192.168.2.121
//0 192.168.2.122
//1 192.168.2.123
//0 192.168.2.124
//0 192.168.2.125
//1 192.168.2.126
//0 192.168.2.127
//1 192.168.2.128
//0 192.168.2.129
for (nLoop = 0; nLoop < 2; nLoop++) //原来为4
{
// Send ICMP echo request
SendEchoRequest(rawSocket, &saDest);
// Use select() to wait for data to be received
nRet = WaitForEchoReply(rawSocket);
if (nRet == SOCKET_ERROR)
{
ReportError("select()");
nErrorNum = nErrorNum+1;
break;
}
if (!nRet)
{
printf("\nTimeOut");
nErrorNum = nErrorNum+1;
break;
}
// Receive reply
dwTimeSent = RecvEchoReply(rawSocket, &saSrc, &cTTL);
// Calculate elapsed time
dwElapsed = GetTickCount() - dwTimeSent;
printf("\nReply from: %s: bytes=%d time=%ldms TTL=%d",
inet_ntoa(saSrc.sin_addr),
REQ_DATASIZE,
dwElapsed,
cTTL);
}
printf("\n");
nRet = closesocket(rawSocket);
if (nRet == SOCKET_ERROR)
ReportError("closesocket()");
return nErrorNum;
}
[解决办法]
1。网上有 ping 的原代码,但在 win7 下有 权限问题
2。 system ("ping 127.0.0.1 > 1.txt"); 分析 1.txt