简体   繁体   中英

Why will socket connection to port 23 not work?

I have this small test socket connection class:-

import java.net.Socket;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.IOException;

public class TestTelnet {

public static void main(String args[]) throws Exception {
    Telnet telnet = new Telnet(); 
    Socket socket = null ;
    socket = new Socket("localhost", 23);
    socket.setKeepAlive(true);
    BufferedReader r = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        BufferedWriter w = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    System.out.println(r.readLine());
    socket.close();
}
}

It works perfectly well when I use another port (for example 25 for SMTP) and the println of r.readLine works brilliantly. I can also connect to port 23 via the command prompt (telnet localhost 23) and I get the following returned:-

Ubuntu 8.10 my-laptop login:

But when I try and connect to port 23 using my java class, it just hangs on the readLine println. Does anyone know why this is?

I guess it's because your expecting a line (with CR or CRLF termination) but your telnet service does not send a complete line. Try using r.read() instead of r.readLine()

Telnet is a protocol, and is probably expecting you to do option negotiation. Once you send it something useful, it will probably send you something useful.

see: http://www.faqs.org/rfcs/rfc854.html

Telnet is both a protocol and an application

When you use telnet the application to a machine, the application sends the protocol information so the remote machine may respond.

Since you say it stay there, it means it is working, it's just you are not following the protocol.

The protocol is described here:

http://tools.ietf.org/html/rfc854

What you're trying to do here is write a telnet application.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM