/* surfport.c

 Usar: ./surf <host>

 by CoKi

 [ 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 DATAMAX 300
#define TIMEOUT 3
#define ERROR -1

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

  int sockfd, i, numbytes;
  char buf[DATAMAX];
  struct hostent *he;
  struct sockaddr_in dest_dir;
  struct timeval timeout;
  unsigned int puerto[] = { 21, 22, 23, 25, 110 };
  fd_set readfds;

  printf("\nsurf.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);
  }

for(i=0; i<5; i++) {
  
  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[i]);
  dest_dir.sin_addr = *((struct in_addr *)he->h_addr);
  bzero(&(dest_dir.sin_zero), 8);

  printf("Puerto %u:\t", puerto[i]);

  if(connect(sockfd, (struct sockaddr *)&dest_dir, sizeof(struct sockaddr)) == ERROR) {
    printf("Cerrado\n");
  }
  
  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");
  }

  bzero(buf, sizeof(buf));
  numbytes=recv(sockfd, buf, DATAMAX-1, 0);
  
  buf[numbytes+1] = '\0';

  printf(buf);
  close(sockfd);
}
printf("\n");
}
