我正在研究一个小程序来检查我的网络服务器是否活着和其他东西,程序读取带有IP地址或主机名的测试列表并检查网页中的字符串;如果答案是真的,那么任何事情都可以正常工作,如果不是我的程序退出。我究竟做错了什么?这是我的代码:
#include <stdio.h>
#include <string.h>
#include <winsock.h>
#pragma comment(lib, "wsock32.lib")
int isAlive(const char *addr)
{
struct sockaddr_in blah;
struct hostent *he;
WSADATA wsaData;
int i;
WORD wVersionRequested;
SOCKET sock;
char buff[1024];
char *ex;
ex="GET /alive.php HTTP/1.0\n\n";
char *fmsg="ALIVE";
wVersionRequested = MAKEWORD(1, 1);
if (WSAStartup(wVersionRequested , &wsaData)){
printf("Winsock Initialization failed.\n");
exit(1);
}
if ((sock=socket(AF_INET,SOCK_STREAM,0))==INVALID_SOCKET){
printf("Can not create socket.\n");
exit(1);
}
sock = socket(AF_INET,SOCK_STREAM,0);
blah.sin_family = AF_INET;
blah.sin_port = htons(80);
blah.sin_addr.s_addr = inet_addr(addr);
if ((he=gethostbyname(addr))!=NULL){
memcpy((char *)&blah.sin_addr.s_addr,he->h_addr,he->h_length);
}
else{
if((blah.sin_addr.s_addr=inet_addr(addr))==-1){
WSACleanup();
exit(1);
}
}
if (connect(sock,(struct sockaddr*)&blah,sizeof(blah))==0){
send(sock,ex,strlen(ex),0);
recv(sock,buff,sizeof(buff),0);
if(strstr(buff,fmsg)!=NULL){
printf("ALIVE: %s\n", addr);
}
}
closesocket(sock);
WSACleanup();
return(1);
}
int main(int argc,char *argv[])
{
if(argc!=2){
printf("Usage: checkalive [webservers list]\n");
return(1);
}
char *inname = argv[1];
FILE *infile;
char line_buffer[BUFSIZ];
char line_number;
infile = fopen(inname, "r");
if (!infile) {
printf("Couldn't open file %s for reading.\n", inname);
return 0;
}
line_number = 0;
while (fgets(line_buffer, sizeof(line_buffer), infile)) {
++line_number;
//printf("%s", line_buffer);
isAlive(line_buffer);
}
return 0;
}