/*
 * Cubbi's simple telnet client (actually, a TCP terminal)
 * (it won't connect to telnet port because it does not support TELNET 
 *  control sequences, but you can connect to ftp-control port 21, or
 *  irc ports or smtp or whatever)
 *
 * (c) 1999 Sergey Zubkov
 */
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <signal.h>

int main()
{
 int fd; // will be the socket's file handle
 FILE* sock; // will be the sockets's file descriptor

 struct sockaddr_in server;
 struct hostent* he;
 char* name="localhost";  // <- hostname to connect
 char* errmsg;

 // Fill out the structures
 server.sin_family=AF_INET;
 server.sin_port=htons(21);  // <- port
 // server.sin_addr.s_addr=inet_addr("127.0.0.1"); // <- if you already
 //	know IP address, put it in there, and don't call gethostbyname
 if ((he=gethostbyname(name)))
	memcpy(&server.sin_addr,he->h_addr,he->h_length);
 else {
	fprintf(stderr,"no IP address for %s: %s\n",name,errmsg);
	return -1;
 }
 fprintf(stderr,"trying %s at port %d\n",
	inet_ntoa(server.sin_addr),(int)ntohs(server.sin_port));
// the next two functions open and connect a socket
 fd=socket(AF_INET,SOCK_STREAM,0);
 if (connect(fd,(struct sockaddr *)&server,sizeof(server)) == -1) {
	fprintf(stderr,"cannot connect %s\n",inet_ntoa(server.sin_addr));
	return -1;
 }
 // Now I have a file descriptor fd. I can use send/recv with it, or
 // read/write, or poll/select. Or fdopen it like I will now
 if(fork()) {
	 // parent
	 fclose(stdin);
 	 sock=fdopen(fd,"r");
	 while(1) {
		 printf("%c",fgetc(sock));
		 fflush(sock);
		 fflush(stdout);
	 }
 } else {
	 //child
	 fclose(stdout);
 	 sock=fdopen(fd,"w");
	 while(1) {
		 fprintf(sock,"%c",fgetc(stdin));
		 fflush(sock);
		 fflush(stdin);
	 }
 }
}
