【求教】怎么用c语言来判断网络是否通
比如 用ping 192.168.1.12 让c语言判断 是通还是不通怎么来实现
c
网络
------解决方案--------------------
仅供参考#include
#include
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
------解决方案--------------------
int Ping(LPCSTR pstrHost)
{
int nErrorNum=0;
SOCKET rawSocket;
LPHOSTENT lpHost;
struct sockaddr_in saDest;
struct sockaddr_in saSrc;
DWORD dwTimeSent;
DWORD dwElapsed;
u_char cTTL;
int nLoop;
int nRet;
// Create a Raw socket
rawSocket = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
if (rawSocket == SOCKET_ERROR)
{
ReportError("socket()");
return -1;
}
// Lookup host
lpHost = gethostbyname(pstrHost);
if (lpHost == NULL)
{
fprintf(stderr,"\nHost not found: %s\n", pstrHost);
return -2;
}
// Setup destination socket address
saDest.sin_addr.s_addr = *((u_long FAR *) (lpHost->h_addr));
saDest.sin_family = AF_INET;
saDest.sin_port = 0;
// Tell the user what we're doing
printf("\nPinging %s [%s] with %d bytes of data:\n",
pstrHost,
inet_ntoa(saDest.sin_addr),
REQ_DATASIZE);
// Ping multiple times