/* simple-surf.c

   Use: ./simple-surf <host> <port>
   
   by CoKi <coki@nosystem.com.ar>
   http://www.nosystem.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 BUFFER 1024
#define TIMEOUT 2

int main(int argc, char *argv[]) {
  int sockfd;
  struct sockaddr_in dest;
  char buffer[BUFFER];
  struct hostent *he;
  struct timeval timeout;
  fd_set readfds;
  timeout.tv_sec = TIMEOUT;
  timeout.tv_usec = 0;

  if(argc != 3) {
    printf("Usage: %s <host <port>\n", argv[0]);
    exit(1);
  }

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

  if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
    perror("socket");
    exit(errno);
  }

  bzero(&dest, sizeof(dest));
  dest.sin_family = AF_INET;
  dest.sin_port = htons(atoi(argv[2]));
  dest.sin_addr = *((struct in_addr *)he->h_addr);

  if(connect(sockfd, (struct sockaddr *)&dest, sizeof(dest)) != 0) {
    perror("connect");
    exit(errno);
  }
  
  FD_ZERO(&readfds);
  FD_SET(sockfd, &readfds);
  
  select(sockfd+1, &readfds, NULL, NULL, &timeout);
        
  if(!FD_ISSET(sockfd, &readfds)) {
    printf("timeout!!\n");
    exit(1);
  }

  bzero(buffer, BUFFER);
  recv(sockfd, buffer, sizeof(buffer), 0);
  printf("%s", buffer);

  close(sockfd);
  return 0;
}

