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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With