-5

我开发了一个小 C 程序来检查我的网络服务器是否还活着和其他东西,该程序读取带有 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;
}
4

1 回答 1

1

我建议首先阅读退出调用的结果。然后我建议通过您的 isAlive 代码并仔细检查错误处理......

于 2013-01-27T08:30:25.393 回答