Java - How To Determine If Server Is FTP Or SFTP?
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...
}
}
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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM