Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java simple telnet client using sockets

I have read plenty of things on the topic, how telnet is a protocol, not a simple socket connection, waiting for newline characters, use of external libraries and whatnot...

The bottom line is that I need a quick and dirty java telnet application up and running, not necessarily scalable and not necessarily pretty, so I'm trying to avoid the use of libraries, system function calls and the like. I have been trying and testing and so far, when trying to log into a router (through telnet of course) I have got... nothing.

Here is a snipped of the code that I have been using so far, please someone point me at the right direction because I don't know what else I should try, because I'm certain that it has to be something really simple and silly that I'm missing. Thanks in advance!

Socket socket = new Socket("192.168.1.1", 23);
socket.setKeepAlive(true);
BufferedReader r = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter w = new PrintWriter(socket.getOutputStream(),true);

int c=0;
while ((c = r.read()) != -1)
    System.out.print((char)c);

w.print("1234\r\n"); // also tried simply \n or \r
//w.flush();
//Thread.sleep(1000);

while ((c = r.read()) != -1)
    System.out.print((char)c);

w.print("1234\r\n");
//Thread.sleep(1000);

while ((c = r.read()) != -1)
    System.out.print((char)c);

socket.close();
like image 727
Oscar Wahltinez Avatar asked Jun 18 '11 23:06

Oscar Wahltinez


1 Answers

It's hard to know what's wrong with your example without testing against your particular router. It might be a good idea to use a library, for instance http://sadun-util.sourceforge.net/telnet_library.html looks like an easy one to use.

Also this site says the following:

In order to carry on the conversation, a command is issued by simply sending it on the socket's outputstream (and using the telnet newline sequence \r\n):

 String command="print hello"; 
 PrintWriter pw = new PrintWriter(
      new OutputStreamWriter(s.getOutputStream()), true);
 pw.print(command+"\r\n");

If the session appears to hang after login, avoid to wrap the StreamWriter into a PrintWriter and instead run an explicit flush() at the end:

 Writer w = new OutputStreamWriter(s.getOutputStream());
 w.print(command+"\r\n");
 w.flush();

This might actually be the problem with your code.

like image 65
jontro Avatar answered Sep 18 '22 12:09

jontro