/*
*  C Implementation: dateclient
*
* Description: connects to a server, reads till end of stream, exits
*
*
* Author: Konrad Rosenbaum <konrad@silmor.de>, (C) 2006
*
* Copyright: See COPYING file that comes with this distribution
*
*/

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

int main(int argc,char**argv)
{
	int port,sock;
	char*tmp;
	struct sockaddr_in sa;
	struct hostent*hent;
	/*check arguments*/
	if(argc!=3){
		fprintf(stderr,"Usage: %s <host> <port>\n",*argv);
		return 1;
	}
	port=strtol(argv[2],&tmp,0);
	if(*tmp!=0 || port<1 || port>65535){
		fprintf(stderr,"Port must be a number in the range 1<=x<=65535!\n");
		return 1;
	}
	/*retrieve IP from host name*/
	hent=gethostbyname(argv[1]);
	if(hent==0){
		fprintf(stderr,"Unable to retrieve IP for host %s.\n",argv[1]);
		return 1;
	}
	if(hent->h_addr_list[0]==0){
		fprintf(stderr,"Host record for %s does not contain any IP.\n",argv[1]);
		return 1;
	}
	/*create socket*/
	sock=socket(PF_INET,SOCK_STREAM,0);
	if(sock<0){
		fprintf(stderr,"Failed to retrieve socket: %s\n",strerror(errno));
		return 1;
	}
	/*connect it to host/port*/
	sa.sin_family=AF_INET;
	memcpy(&sa.sin_addr,hent->h_addr_list[0],hent->h_length);
	sa.sin_port=htons(port);
	if(connect(sock,&sa,sizeof(sa))!=0){
		fprintf(stderr,"Unable to connect: %s.\n",strerror(errno));
		return 1;
	}
	/*loop: read data, dump it on stdout*/
	for(;;){
		int r;
		char buf[1024];
		r=read(sock,buf,sizeof(buf));
		if(r==0)break;
		if(r<0){
			fprintf(stderr,"Error while reading: %s\n",strerror(errno));
			break;
		}
		write(STDOUT_FILENO,buf,r);
	}
	/*close socket*/
	close(sock);
	/*success*/
	return 0;
}