Java FTP connection timed out - java

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.

Related

How to check if FTP server is alive?

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").

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?

Socket: could not connect to server or specific port

I am trying to connect server by port and Host Name.
I find one program but when i am trying to run it will show following Exception
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
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:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:208)
at sample.Echoclient2.main(Echoclient2.java:31)
Couldn't get I/O for the connection to: 127.0.0.1
Java Result: 1
Here is my code which i use.
public class Echoclient2 {
public static void main(String[] args) throws IOException {
String serverHostname = new String ("127.0.0.1");
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " +
serverHostname + " on port 10008.");
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket(serverHostname, 10008);
System.out.println("server name"+Inet4Address.getByName(serverHostname));
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
System.out.println("Connection accepted " +
echoSocket.getInetAddress() + ":" +
echoSocket.getPort());
} catch (UnknownHostException e) {
e.printStackTrace();
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
e.printStackTrace();
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
String userInput;
System.out.println ("Type Message (\"Bye.\" to quit)");
while ((userInput = stdIn.readLine()) != null)
{
out.println(userInput);
// end loop
if (userInput.equals("Bye."))
break;
System.out.println("echo: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
What i need:
1. I need to send some message to server and want response from server. Suppose i send "I am user of stackoverflow" then server should give any response like return same String or convert in uppercase or something else.
Some Questions:
1. I write client Java File but whether i need to write server java file.
2. Can we send request by using ip and port.
3. Can we use host name.
4. Any echo server name? i need to send message to this server want to know response.
5. I try both server,java and client.java then i got result? is this solution for me.
1. I write client Java File but whether i need to write server java file.
Yes, you either need to write your own server (if the server should fulfill some unique requirements) or connect to an existing one. The message "connection refused" indicates that no server is running at the port you are trying to connect to.
2. Can we send request by using ip and port.
Yes.
3. Can we use host name.
Yes. You need either IP or hostname, and the port.
4. Any echo server name? i need to send message to this server want to know response.
You can setup an echo server on your machine so that you can first focus on coding your client. There is a Standard Echo server defined at port 7. Setup depends on your operating system environment - On Ubuntu Linux, I had to install the xinetd package and enable the echo server in /etc/xinetd.d/echo. Then, you can verify if the server is running by using the telnet program:
andreas#ubuntu:~$ telnet localhost 7
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello
Hello
Using telnet to connect to any port is also a common technique to verify if a server is running and reachable. With the example from your question, you could check with telnet 127.0.0.1 10008 whether a server is running on the port you specified - you will get the same connetion refused as from your Java program if no server is available.
5. I try both server,java and client.java then i got result? is this solution for me.
Not sure which server and client you are referring to.
Some additional references:
All about sockets (also includes "Writing a Client/Server pair")
Enabling desired xinetd protocols
Java Tutorial: Echo client in Java
You have to run your server program also in local host. You are getting this exception because of 10008 port not ruining on your machine.
Some Question:
I write client Java File but whether i need to write server java file.
either you can write a server program or you can connect to a remote server. In that
case you should have both ip and running port in remote server.
Can we send request by using ip and port.
Yes You required both to send a message.
Can we use host name.
If you machine can resolve your host name you can do it. Otherwice you can use ip address
Any echo server name? i need to send message to this server want to know response.
I have no idea about this , need to search on web.
I try both server,java and client.java then i got result? is this solution for me.
Yes.

SocketException on remote server

I have a problem when trying to connect to a remote server.
SocketException: Invalid argument or cannot assign requested address
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
Here is how i create the socket
if (socket == null) {
socket = new Socket();
try {
socket.setReuseAddress(true);
socket.setTcpNoDelay(true);
} catch (SocketException ex) {
}
}
dstAddress = new InetSocketAddress(server, dstPort);
srcAddress = new InetSocketAddress("localhost", srcPort);
socket.bind(srcAddress);
socket.connect(dstAddress);
Everything works fine on localhost.
http://comments.gmane.org/gmane.comp.finance.moneydance.general/5389
This sometimes occurs on other platforms - it used to occasionally
occur on earlier versions of Mac OS X. The solution definitely lies
outside of Moneydance since MD is requesting (through Java) to open a
standard network connection and the system is saying that it is unable to do so.
The only solution I have found for this is to reboot your computer.
If you are also running other software that uses a lot of network
resources, try not running that for a while to see if it makes a
difference.
Remove the bind() call. It is not required.
Try running your program with
-Djava.net.preferIPv4Stack=true
when connecting to the remote system.

Java Networking: Connection refused - Yes, my server is running

I'm getting following error when my client tries to connect to my server socket:
java.net.ConnectException: Connection refused: connect
But, my server is really running, on the same machine. I try to connect to it by using the external IP of my router. But when I try to connect with "localhost", it works. And, yes I did port forwarding correcly in my router. Even canyouseeme.org can connect to my server (The site says: "success" and in my server-log appears that someone connected with the server.)
So, is it for one or another reason impossible to connect to the same machine (or to a machine in the same network) via an external IP? Or is this something typical for Windows? (Normally, I use Linux)
I also tried to completely disable Windows Firewall.
ServerSocket:
public ServerSocket ssocket;
public List<ClientHandler> handlers;
public Server(int port) { // Constructor
try {
ssocket = new ServerSocket(port);
this.handlers = new ArrayList<ClientHandler>();
IpSharingManager.uploadData(Utilities.getPublicIp(), port);
} catch (Exception e) {
e.printStackTrace();
System.exit(-1);
}
}
Client:
public InvisibleClient(String host, int port) {
try {
System.out.println("Trying to connect to " + host + ":" + port);
this.host = host;
this.socket = new Socket(host, port);
this.bis = new BufferedInputStream(this.socket.getInputStream());
this.bos = new BufferedOutputStream(this.socket.getOutputStream());
this.console = new RemoteConsole(this.socket);
initializeCommunication();
System.out.println("Successfully connected!");
new Thread(this, "Client Thread").start();
} catch (Exception e) {
e.printStackTrace();
System.out.println("No server available");
}
}
Thanks
Some routers doesn't allow the internal network to connect to the external IP address of the router.
You can try to use telnet to connect to your server socket. If telnet isn't able to establish a connection, it's likely a networking problem.
Add the java.exe process and the port to your firewall exception list?
edit: Just read you already tried that. All I can suggest is make sure the network is not blocking that port. (routers)
Have You tried running it with JVM option: java.net.preferIPv4Stack=true ?
For what I see in your code, you missed the part where you accept the conection, after instantiating the server socket you need ssocket.accept() to accept conections and then you have to start reading the outputstrem from the socket

Categories