Ad

Java - How To Determine If Server Is FTP Or SFTP?

- 1 answer

I'm making a class in Java that downloads a specific file from a server. I have a method that can download directly from an FTP server and one from an SFTP server.

Without any assumptions being made on the hostname (without checking if it starts with ftp:// or sftp://, as sometimes the server may be local), is there any way to determine if a server is FTP or SFTP, and therefore which method to use?

Ideally, I'd like to determine programmatically, and not just to try the alternative if it fails. Thanks for any help in advance!

EDIT: For anyone interested, my very basic and definitely not perfect solution is somethign like this:

private int determineServerProtocol(String host, String port) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try (Socket socket = new Socket(host, Integer.parseInt(port))) {
            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            result = in.readLine();
            out.close();
            in.close();
        } catch (NumberFormatException | IOException e) {
            e.printStackTrace();
        }
        if (result.contains("SSH")) {
            System.out.println("Server is SFTP");
            // do things...
        } else {
            System.out.println("Server is FTP");
            // do things...
        }
    }
Ad

Answer

You can do a telnet. Apache Commons provides a client side of many intenet protocols.

https://commons.apache.org/proper/commons-net/

And then analyze the answer.

As far as I know, all SSH servers answer something with SSH inside.

telnet demo.wftpserver.com 2222
Trying 199.71.215.197...
Connected to demo.wftpserver.com.
Escape character is '^]'.
SSH-2.0-WingFTPServer

Not SSH

telnet  ftp.funet.fi 21
Trying 193.166.3.2...
Connected to ftp.funet.fi.
Escape character is '^]'.
220 FTP Welcome
Ad
source: stackoverflow.com
Ad