How to check if FTP server is alive? - java

I need to check if a FTP server is alive, is this server:
ftp://speedtest.tele2.net/upload/
I tried with this code:
FTPClient ftp = new FTPClient();
try {
ftp.setConnectTimeout(5000);
ftp.setDefaultTimeout(5000);
ftp.setDataTimeout(5000);
ftp.connect(urlString);
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
ftp.disconnect();
}
The problem is that is returning this exception:
java.net.UnknownHostException: Unable to resolve host "ftp://speedtest.tele2.net/upload/": No address associated with hostname
How can this be achieved?

The connect method takes a hostname, not a URL.
The ftp:// part is useless; this is an FTP client, it can't do anything else.
The /upload part is also useless; it can't go to that path until after connecting. Hence, taking a URL just doesn't make sense, so the API is properly the designed.
Call .connect("speedtest.tele2.net").

Related

Connection to an SFTP via apache camel

Usually I connect to the Sftp server via camel route, but the problem is that in this ftp I don't have permission to delete the files and every day I have to take the file of the day, so I wanted to connect via code and then check the upload date:
val sftp = FTPSClient()
private fun sftpConnection() {
try {
sftp.connect(host, port)
sftp.login(user, password)
sftp.enterLocalPassiveMode()
} catch (e: Exception) {
logger.error("Error connecting to SFTP: ${e.message}", e)
}
}
in this way the connection did not work, can anyone tell me how I could do it?

unable to connect to unc location using jcifs

I have some remote locations that falls under same domain.When i access the remote location from windows then it opens without asking for credentials.But if i aceess the location using java code (jcifs) then it gives me this exception
jcifs.smb.SmbAuthException: Logon failure: unknown user name or bad
password
Java code is
String path=convertToSmb(loc);
NtlmPasswordAuthentication auth=new NtlmPasswordAuthentication(path, userName, passwd);
SmbFile sFile=null;
try {
sFile=new SmbFile(path,auth);
sFile.connect();
boolean sFileExists = sFile.exists();
logger.info("checkUNCLocation [END] with :: sfileExists :: "+sFileExists);
return sFileExists;
} catch (MalformedURLException e) {
logger.error(e.getMessage(), e);
return Boolean.FALSE;
} catch (IOException e) {
logger.error(e.getMessage(), e);
return UNCNetworkConnectionWrapper.connectUNCNetwork(loc, userName, passwd);
}finally{
sFile=null;
//jcifs.Config.setProperty("jcifs.smb.client.disablePlainTextPasswords", Boolean.TRUE.toString());
}
i tried deleting all connections using net use delete but windows still did not ask for credentials
Logging also shows correct credentials.
Please guide what should be the reason.
Have you tried to set the userName and the password??
How Windows doing it is by try to connect the server using the current credentials, If you are connected with your user and you are trying to connect to other machine in the same domain, the connection will succeed , because your credentials is valid in this Domain.
Try to use your own credentials to connect to "this" server.

Java game socket network router issue

Good day,
I have a java game that I want to play with a friend over network, I have implemented Sockets and tested the game on my pc using localhost as address, but was unable to connect to the external ip of my pal's pc, presumably due to us both being behind routers.
Here is the code of host/client:
CLIENT:
try {
socket = new Socket(inputHostIp(), 5555);
} catch (IOException e) {
e.printStackTrace();
}
SERVER:
try {
hostServer = new ServerSocket(5555);
} catch (IOException e1) {
e1.printStackTrace();
}
listenForUserConnection();
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
Socket socket = null;
try {
socket = hostServer.accept();
} catch (IOException e) {
e.printStackTrace();
continue;
}
joined(socket);
}
The exception I am getting now is
java.net.ConnectException: Connection timed out: connect
On trying to init I/O:
java.net.SocketException: Socket is not connected
java.net.Socket.getInputStream/java.net.Socket.getOutputStream
I have set up port forwarding with the chosen port number (5555) linked to the internal ip on both our machines.
What are my options for getting this to work?
ADDENDUM:
We have also tried using Hamachi to create a virtual LAN, but there seems to be an issue with that - we can’t ping one another even through that, it diagnoses with an issue -
Tunnel:
VPN domain's tap device is down
Local results:
Adapter configuration:
Cannot get adapter config
Traffic test: Cannot complete test
Peer results: [160-056-951]
Adapter configuration: OK
Traffic test: Inbound traffic blocked, check firewall settings
I have tried shutting down firewalls, hamachi issues changed to just ‘cannot get adapter config’, but otherwise no results.
On my pc, however, I got a version of windows that doesn’t seem to display Firewall setting properly, if you think it’s likely an issue, can you tip me on how to test my firewall?

SMTPClient set timout for an open port

My problem is: I need to discovery if one IP and Port is running a SMTP service.
To do this, I'm using SMTPClient to try open a connection. I'm using the code below.
private static boolean validateSMTP(String ip, int port, int timeOut) {
SMTPClient smtp = new SMTPClient();
try {
smtp.setConnectTimeout(timeOut);
smtp.connect(ip, port);
return true;
} catch (SocketException e) {
LogAplication.Warning("Ops... something wrong", e);
} catch (IOException e) {
LogAplication.Warning("Ops... something wrong", e);
}
finally{
smtp = null;
}
return false;
}
It's working fine and I've gotten the expected results, but the timeOut has been my problem.
E.g: If I try ip: 127.0.0.1 and port 80 (IIS open port) the connect step takes a long (much more than is defined in timeout) to throw an exception
java.net.SocketException: Connection reset
How can I set timeOut for this case? Or existis another way to do my simple test ?
After take a look at grepCode, I found this for method connect(string host, int port):
Opens a Socket connected to a remote host at the specified port and
originating from the specified local address and port. Before
returning, _connect Action() is called to perform connection
initialization actions.
As the port is opened by another service, the socket is opened, not causing timeOut (by socket), but the exception was thrown by "connectAction()"
So I needed to set a global timeOut for my SMTPClient, which is used by socket connection and inside of "connectAction()" . And I did this to solve my problem:
smtp.setDefaultTimeout(timeOut);
With this, now I've the expected results for, open ports which throws exceptions and of course, the successfully connection for SMTP services.

Java FTP connection timed out

I am working on a project which will later upload a few files to an FTP server after they are modified...I have everything but uploading the file figured out. I can successfully connect to the FTP server, but once the file goes to upload, the program hangs for a couple minutes, then it states that it timed out.
java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at org.apache.commons.net.ftp.FTPClient._openDataConnection_(FTPClient.java:762)
at org.apache.commons.net.ftp.FTPClient._storeFile(FTPClient.java:565)
at org.apache.commons.net.ftp.FTPClient.__storeFile(FTPClient.java:557)
at org.apache.commons.net.ftp.FTPClient.storeFile(FTPClient.java:1795)
at AdvertisementCreator.main(AdvertisementCreator.java:128)
e
Here is the code I have for the FTP connection: (Keep in mind I omitted the login details)
FTPClient fClient = new FTPClient();
try {
fClient.connect(server, port);
showServerReply(fClient);
int replyCode = fClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
System.out.println("Operation failed. Server reply code: " + replyCode);
return;
}
boolean success = fClient.login(user, pass);
showServerReply(fClient);
if (!success) {
System.out.println("Could not login to the server");
} else {
System.out.println("You are now logged on!");
loginLoop = false;
}
fClient.enterLocalPassiveMode();
fClient.setFileType(FTP.BINARY_FILE_TYPE);
File localFile = new File("files\\shared.txt");
String remoteFile = "shared.txt";
InputStream inputStream = new FileInputStream(localFile);
System.out.println("Start uploading the file");
boolean done = fClient.storeFile(remoteFile, inputStream);
inputStream.close();
if (done) {
System.out.println(remoteFile+" has been uploaded successfully");
}
} catch (IOException ex) {
System.out.println("Oops! Something wrong happened");
ex.printStackTrace();
}finally {
try {
if (fClient.isConnected()) {
fClient.logout();
fClient.disconnect();
System.out.println("FTP Disconnected");
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
I have never really messed with Apache Commons FTP until today. If anyone could provide some insight, I would greatly appreciate it
Edit: I forgot to mention that before adding the following line, the file transferred, but when I tried to open it on the server, it was empty.
fClient.enterLocalPassiveMode();
fClient.setFileType(FTP.BINARY_FILE_TYPE);
This is a common conectivity problem that you'll have to debug first:
First, ensure the name of the server is correctly typed. Also ensure that you have properly specified a port (if, for some reason, it is not the well-known FTP port 21).
Then, ensure you have TCP conectivity between your local host and the remote FTP server: For example, open a command shell and try to execute "telnet 21".
If some error happens, you CAN NOT connect to that server. It is not accessible from your location.
Else, if the terminal clears out, then you can exit: A connection has been succesfully made. In this case, check if you are using a proxy in your system setup (in windows, for example, it is seen on Control Panel\Internet Options\Connections\LAN). If yes, you have to set the same proxy parameters to the JVM when running it:
java -Dftp.socksProxyHost=<proxy host> -Dftp.socksProxyPort=<proxy port> -Djava.net.socks.username=<proxy username> -Djava.net.socks.password=<proxy user password> -classpath ... MainClass
Look all the networking properties in Java.
And yet another possibility is that you have some local firewall blocking this connection. Check it out and read the firewall's manual.

Categories