Tuesday, February 28, 2012

How to Code a Telnet Application Using Java

How to Write a simple Telnet Application using Java Language.

What is Client-Server Model for Web based Applications?
Network is a system which connects two or more communication devices to communicate. A network without any services and applications are not very useful. Basically if we want to use a network in a more useful way we need application which provide some service to a user using the Network.
Server is also a communication device which will provide some service to the clients. When we want to get some service (Eg: Sending an e-mail ) we have to establish a connection to the server. After we connect to the server we can get some service from it. 
So basically Client-Server Model means there is a server which provides some services and there are clients (most of the time it's a program runs in a computer according to some protocol) which can connect to that server to get some services.



What is a Port importance of a port?


If we refer the OSI reference module we find an application layer. In that application layer we can have several application's network portion. Assume we have two communicating devices.

                Device 01                                Device 02














Here he devices have several applications on the Application layer. Assume the App X on the device one wants to communicate with App y on the Device two. So they have to connect to the network using the same port number. Every port has a defined protocol to use. (If we are communicate between two application we need some set of rules {Protocol}). Eg: SMTP port no 25, HTTP port No 80 etc

What is a Telnet Application?

It's basically an application which provides some remote login to Telnet protocol supported server. Here in the application level we are using the telnet protocol. In the Below code has the minimum amount of implementation of telnet protocol to established a connection.

What are the minimum Requirements to run a Telnet Application?

Basically we need a server and a client which supports the telnet protocol. Here we are writing this program to run in a normal computer. So the User may insert several lines of command. We just can't forward it to server because our program has to obey the Telnet Protocol. For that the code has some kind of a filter to send and receive the commands. Thats the Network Virtual Terminal.
Basically telnet protocol work like this. From one end it specify WILL <some command Option>  then the other side will response with Do<same command option > or DONT <same command Option> . If the one side sends DO<some command option > the Other side will response with WILL <same Command Option> or WONT <same Command Option>  here the WILL, WONT DO and DONT are also encoded with numbers.

The Telnet Application Code

The NVTPriter Class code
 class NVTPrinter extends Thread {   
   NVTInputStream inStream;   
   public NVTPrinter(NVTInputStream in){   
   //super();   
   inStream=in;   
   }   
   public void run(){   
   boolean finished=false;   
   try{   
   do{    
   int i=inStream.read();   
   if(i==-1){   
   finished=true;   
   }    
   else{   
  System.out.print((char)i);   
  System.out.flush();   
  yield();   
  }   
  //System.out.println("\n");   
  }while(!finished);   
  System.out.println("The Connection is aborted....");   
  System.exit(1);   
   }catch(IOException e){   
     System.out.println("Network Virtual Terminal Error");   
  }   
   }  

NVTOutputStream Class
  class NVTOutputStream extends FilterOutputStream{   
   int IAC=255;   
   byte CR=13;   
   byte LF=10;   
   public NVTOutputStream(OutputStream output){   
    super(output);   
   }   
   public void write(int i) throws IOException{   
    super.write(i);   
   }   
   public void println(String s){   
  try{     
    byte [] bytes=s.getBytes();   
    for(int i=0;i<bytes.length;i++){   
     super.write(bytes[i]);   
    }   
     super.write(CR);   
     super.write(LF);   
     super.flush();   
   }catch(IOException e){   
    System.out.println(" Input output Error");   
   }   
   }   
  }   


NVTInputStream Class
 class NVTInputStream extends FilterInputStream{   
   byte IAC=(byte)0xFF;   
   byte DO=(byte)0xFD;   
   byte WILL =(byte)0xFB;   
   byte CR=13;   
   byte LF=10;   
   int wont=252;   
   int dont=254;   
   int bufferSize=1024;   
   OutputStream out;   
   byte [] linebuf=new byte[bufferSize];    
   int numBytes=0;   
   public NVTInputStream(InputStream inStream,OutputStream outStream){   
    super(inStream);   
    out=outStream;   
   }   
   public int read () throws IOException{   
    boolean recIAC;   
    int i;   
    do{   
     recIAC=false;   
     i=in.read();   
     if(i==-1) {   
      return i;   
     }   
     else if(IAC==i){   
      recIAC=true;       
      int cmd=in.read();   
      if(cmd==-1){   
       return cmd;   
      }   
      else{   
       byte b2=(byte)cmd;   
       if(b2==IAC){   
        return 255;   
       }    
       if(b2==WILL){   
       int opt=in.read();   
        if(opt==-1){   
         return opt;   
        }   
       out.write(255);   
       out.write(dont);   
       out.write(opt);   
       out.flush();   
       }   
      if(b2==DO){   
       int opt=in.read();   
        if(opt==-1){   
         return opt;   
        }   
       out.write(255);   
       out.write(wont);   
       out.write(opt);   
       out.flush();   
      }   
      }   
     }   
    }while(recIAC);   
    return i;   
   }   
   public String readLine() throws IOException {   
    numBytes=0;   
    boolean finished=false;   
    do{   
     int i=read();   
     if(i==-1)   
      return null;   
     else{   
     byte b=(byte)i;   
     if(b==LF){   
       if(numBytes>0){   
        if(linebuf[numBytes-1]==13){   
         return new String(linebuf,0,numBytes-1);          
        }   
       }   
      }     
      linebuf[numBytes]=b;   
      ++numBytes;   
     }    
    }while(!finished);   
    return null;   
   }   
  }   

Port Class
 class port extends Thread{   
   Socket con;   
   OutputStream out;   
   NVTInputStream in;   
   NVTPrinter printer;   
   public port(String [] args){   
   System.out.println("length"+args.length);   
    if(args.length!=2){   
     System.out.println("Use: Java Telnet host port");   
     System.exit(2);   
    }   
    String destination=args[0];   
    int port =0;   
    port=Integer.parseInt(args[1]);   
    System.out.println("Connecting to "+destination +" on " +port);   
    try{   
     con=new Socket(destination,port);   
    }catch(UnknownHostException e){   
     System.out.println("Unknown Destination..Try again...");   
     System.exit(3);   
    }   
    catch(IOException e){   
     System.out.println("Error While Creating the Socket");   
     System.exit(3);   
    }   
   try{   
    out=con.getOutputStream();   
    in=new NVTInputStream(con.getInputStream(),out);   
   }catch(IOException e){   
    System.out.println("Input Output Error...");   
    System.exit(3);   
   }   
   System.out.println("Connection Established..");    
   }   
   public void ProcessInput(){   
    try{   
    String line;   
    boolean finished=false;   
    BufferedReader read=new BufferedReader(new InputStreamReader(System.in));   
    do{   
     line=read.readLine();   
     if(line==null){   
      finished=true;   
     }else{   
      try{   
       for(int i=0;i<line.length();i++){   
        out.write(line.charAt(i));   
        out.write('\n');   
     }   
     }catch(IOException e){   
       System.out.println("Input Output Error...");   
        System.exit(3);   
      }   
     }   
    }while(!finished);   
    }  catch(IOException e){   
     System.out.println("Input Output Error...");   
     System.exit(3);   
    }   
  }   
  public void shutdown(){   
   try{   
     con.close();   
    }catch(IOException e){   
     System.out.println("Error Closing the Socket");   
     System.exit(3);   
    }   
   }   
   public void run(){   
    printer =new NVTPrinter(in);   
    printer.start();   
    yield();   
    this.ProcessInput();   
    shutdown();   
   }   
  }  

Sample Telnet Class
 //This is a sample Telnet app coded using java   
  /*   
  * W.M.S Fernando.   
  * 17/02/2012   
  * 11:57 PM   
  *    
  * */   
  import java.net.*;   
  import java.rmi.UnknownHostException;   
  import java.io.*;   
  Public class Telnet {   
   public static void main(String [] str){   
    for(int i=0;i<str.length;i++){   
     System.out.println("<<>>"+str[i]);   
    }   
    port p=new port(str);   
    p.start();   
   }   
  }   



Some Screen Shots