/* webver.c

 Usar: ./webver <host>

 by CoKi <coki@interlap.com.ar>

 [ No System Group ]

*/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>

#define PUERTO 80
#define DATAMAX 300
#define TIMEOUT 3
#define ERROR -1

int main(int argc, char *argv[]) {

  int sockfd, i;
  char buf[DATAMAX], *p, serv[100], c;
  struct hostent *he;
  struct sockaddr_in dest_dir;
  struct timeval timeout;
  fd_set readfds;
  
  printf("\nwebver.c by CoKi\n");
  printf("----------------\n\n");
    
  if(argc!=2) {
    printf("Usar: %s <host>\n\n", argv[0]);
    exit(1);
  }

  if((he=gethostbyname(argv[1])) == NULL) {
    herror("Error");
    printf("\n");
    exit(1);
  }

  if((sockfd=socket(AF_INET, SOCK_STREAM, 0)) == ERROR) {
    perror("Error");
    printf("\n");
    exit(1);
  }

  dest_dir.sin_family = AF_INET;
  dest_dir.sin_port = htons(PUERTO);
  dest_dir.sin_addr = *((struct in_addr *)he->h_addr);
  bzero(&(dest_dir.sin_zero), 8);

  if(connect(sockfd, (struct sockaddr *)&dest_dir, sizeof(struct sockaddr)) == ERROR) {
    perror("Error");
    printf("\n");
    exit(1);
  }

  send(sockfd, "HEAD / HTTP/1.0\n\n", 17, 0);

  timeout.tv_sec = TIMEOUT;
  timeout.tv_usec = 0;
  FD_ZERO(&readfds);
  FD_SET(sockfd, &readfds);

  select(sockfd+1, &readfds, NULL, NULL, &timeout);

  if(!FD_ISSET(sockfd, &readfds)) {
    printf("Tiempo de espera agotado\n\n");
    exit(1);
  }
  
  if(recv(sockfd, buf, DATAMAX, 0) == ERROR) {
    perror("Error");
    printf("\n");
    exit(1);
  }

  if((p=strstr(buf, "Server")) == NULL) {
    printf("No se puede determinar el webserver\n\n");
    exit(1);
  }
  
  for(i=0; i<300; i++) {
    printf("%c", *p++);
    if(*p=='\n') break;
  }
  printf("\n\n");
  close(sockfd);
}

