tags:

views:

180

answers:

5
Process P = Runtime.getRuntime().exec("cmd /c start telnet");    
System.out.println("done running ..");     
OutputStream output = P.getOutputStream();     
BufferedOutputStream out = new BufferedOutputStream(output);     
String S = "open\n"; byte[] BS = S.getBytes();   
out.write(BS); out.close();

The above code is not executing the open command under telnet.

What am I doing wrong?

+1  A: 

How would you know? Since you're not grabbing the input stream, you'll never see the output (or error response) from the telnet application. You really need to hook up all three (output, input and error), and you probably want a separate thread for reading the input and error streams. That should allow you to make some progress on this problem.

Since you don't know in advance how many characters are coming out of your input stream (or telnet's output), you'll want to go with reading only the number of characters given by stream.available(), or simply reading one byte at a time until you get a -1.

Carl Smotricz
He probably got confused, as Process's `getInputStream()` actually returns the stream that has the output of the process.
R. Bemrose
That's understandable. I've solved this problem about half a dozen times and I *still* get confused by the terminology. It's a bit un-intuitive.
Carl Smotricz
+1  A: 

When I run your code on my machine, I get a Windows error dialog stating

Windows cannot find 'telnet'. Make sure you typed the name correctly, and then try again.

Try replacing the first line with

Process P = Runtime.getRuntime().exec("cmd /c C:\\Windows\\system32\\telnet.exe");
Matt Ball
A: 

Get rid of the BufferedOutputStream, it's not useful in that context. If you think you must use it, at least you need to flush() it.

ammoQ
I believe close() implicitly calls flush() ....
alasdairg
@ammo: Nope. Close will automatically flush.
Matt Ball
+1  A: 

Rather than spawn a telnet process which has pathing and platform specific issues, consider just opening a raw socket to the target host on port 25. You'll get a similar input output stream, but your code won't rely on running an external process.

UPDATE: Looks like Apache Commons Net has an implementation of a Telnet client. Might want to give that a try.

basszero
A: 

Rather than running the telnet in the Runtime, you could run a telnet from the Apache Commons libraries. That way you are dealing directly with telnet and not with the process that is running telnet.

G_A