"Connection refused" when connecting to FTP port 990 in Java - java

I made an array of FTPS clients and tried to connect it to the ip & port of my interest. Here is the code.
public class ftptest
{
public static void delete_files(String path, int n) throws IOException
{
String realpath;
for(int i=0 ; i<n ; i++)
{
realpath = path+i;
File file = new File(realpath);
FileUtils.cleanDirectory(file);
}
}
public static void main(String[] args) throws Exception
{
int number = 1;
String ip = "some_ip";
int port = 990;
FTPSClient[] client = new FTPSClient[number];
System.out.println(ip);
System.out.println("port = "+ port);
for(int i = 0; i < number; i++)
{
String path = "D:\\ftptest\\client"+i;
File file = new File(path);
file.mkdir();
client[i] = new FTPSClient(true);
client[i].setRemoteVerificationEnabled(false);
client[i].setTrustManager
(TrustManagerUtils.getAcceptAllTrustManager());
client[i].enterLocalPassiveMode();
client[i].setControlEncoding("UTF-8");
client[i].connect(ip,port);
System.out.println("Connected to " + ip + ".");
}
}
}
but somehow it fails in the client[i].connect(ip, port) part with the error
Exception in thread "main" java.net.ConnectException: Connection refused: >connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:182)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:203)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:296)
at com.samsung.ftptest.ftptest.main(ftptest.java:66)
When it is FTP, not FTPS, it is working fine. Does anybody have any idea why it is not working?
Thank you.

The system on which you're running this, can't connect to port 990 on the server machine. There are a number of reasons this could be the case, including:
The server is not listening on port 990
A firewall is blocking port 990
The first thing you should do is find a client that's successfully connecting to this server using FTPS, and check its configuration:
What port is it configured to use?
Is it using:
explicit FTPS (this is the preferred, standards-compliant way to do FTPS. It connects in plain FTP on port 21, then negotiates up to a secured protocol.
implicit FTPS (this approach has never been a standard, but does occur in the wild. Like HTTPS, a different port (often 990) is used, and an SSL handshakes happens immediately after connection)
Once you know these things, you can put the right port and the right mode into your code.
If you're certain of the port, and that it works from other machines, then a firewall is the likely culprit. Demonstrate that you can't connect, using telnet:
unixprompt$ telnet serverhostname 990
If it hangs, or says "Connection refused", you know that this machine can't reach it. If you get "Connected to ..." you know that at least you have TCP connectivity (then ctrl-] quit to get out).
If you find that it's a firewall, be prepared for a battle. You're struggling with the control connection -- data connections are a whole new fight. Opening firewalls for passive mode explicit FTPS is fairly straightforward, and documented in this IETF draft: https://datatracker.ietf.org/doc/html/draft-fordh-ftp-ssl-firewall-00 -- but firewall admins are notoriously reluctant to do it.

The server probably does not support the (deprecated) implicit FTPS mode.
You better use the explicit mode anyway:
client[i] = new FTPSClient();
// ...
client[i].connect(ip, 21);
(assuming the server does support FTP over TLS/SSL at all)

Related

How to create a ServerSocket Object without the localhost address

Hy guys, my code here to create a simple server works fine with the local host address(127.0.0.1). Here is my code.
import java.io.*;
import java.net.*;
public class Main {
public static void main(String[] args)
{
Zig z = new Zig();
z.start();
}
}
class Zig
{
ServerSocket ss = null;
InetAddress ia = null;
Socket s = null;
private static final int prt = 56540;
Zig()
{
try
{
byte[] addr = {127,0,0,1};
ia = InetAddress.getByAddress(addr);
SocketAddress sa = new InetSocketAddress(ia,prt);
ss = new ServerSocket();
ss.bind(sa);
s = ss.accept();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Zig start()
{
try
{
InputStream i = s.getInputStream();
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String str = null;
while (str != "stp")
{
str = br.readLine();
System.out.println(str);
}
br.close();
isr.close();
i.close();
s.close();
ss.close();
}
catch (IOException e)
{
e.printStackTrace();
}
return this;
}
}
My question is, how can I use the router's IP - 192.168.8.1 instead of 127.0.0.1? I also tried the IP address from http://whatsmyip.org but still got this exception:
java.net.BindException: Cannot assign requested address: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(DualStackPlainSocketImpl.java:106)
at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:387)
at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:190)
at java.net.ServerSocket.bind(ServerSocket.java:375)
at java.net.ServerSocket.bind(ServerSocket.java:329)
at Zig.<init>(Main.java:26)
at Main.main(Main.java:8)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Exception in thread "main" java.lang.NullPointerException
at Zig.start(Main.java:38)
at Main.main(Main.java:9)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
I wanted to create a simple server with that i can access remotely with another computer both having internet connection.
Or is there a way I can make communication between two computers over internet?
Regards.
how can I use the router's IP - 192.168.8.1
You cannot use the router's IP. You should use the IP thats available in the system.
Note this error :
> java.net.BindException: Cannot assign requested address: JVM_Bind
The bind is failing because the address isn't that of the system.
If you want your 2 devices to communicate via LAN (local network) you can use the addresses your router assigned to these devices (that's the 192.168.8.X address you mentioned. EDIT: As Prabhu mentioned, use the devices IP Address, not the routers IP-Address! You can usually find the IPs your router assigned to connected devices in your routers admin-interface). Remember that your router might assign a different adress to the same devices in the future. Most routers come with a function that always assigns the same IP to a specific device. Also, some routers block communication between local devices (i.e. between wired and WiFi devives) for security reasons. Check your router's configuration for more information and configuration options!
If you want your devices to connect via internet you have to use your routers global IP-address (thats probably the one you found out using whatsmyip).
Additionally, your router usually just blocks incoming requests from the internet for security reasons. Again, your Router probably has a function called Port forwarding, which allows you to redirect requests to a specific device (and a specific port at that device) in your local network. Use this with care, as this opens (a part) of your routers built-in security mechanisms.
Finally, depending on your provider, you may have a IPv4 address (see Wikipedia) that you share with other customers (So called DS-Lite (Wiki). In this case, you're network is not reachable from the IPv4-internet at all and your only chance is to use the IPv6 Protocol (if available).
Hope that helps.

Troubleshoot connecting client to server in java

I have been having this problem for some time now and although my efforts and my friends help I can't seem to get past this problem .
My problem is I am trying to establish a connection between client and a server using sockets its very common actually, but for some reason client can't seem to connect to the server don't know why , here is my attempts to solve the problem
1- I used http://portforward.com/ to open the used port on my router which is of type "zhone"
2- I changed the port multiple times and every time I used PFPortChecker to see if my port is open
my code is fairly simple it opens server and when client connects to it , the server sends the date and time
my server code looks like this
public class DateServer {
/** Runs the server. */
public static void main(String[] args) throws IOException {
ServerSocket listener = new ServerSocket(6780);
try {
while (true) {
Socket socket = listener.accept();
try {
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(new Date().toString());
} finally {
socket.close();
}
}
} finally {
listener.close();
}
}
}
my client code looks like this
public class DateClient {
/** Runs the client as an application. First it displays a dialog box asking for the IP address or hostname of a host running the date server, then connects to it and displays the date that it serves. */
public static void main(String[] args) throws IOException {
//I used my serverAddress is my external ip address
Socket s = new Socket(serverAddress, 6780);
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
JOptionPane.showMessageDialog(null, answer);
System.exit(0);
}
}
even though I continued my attempts
3- I closed my firewall just in case
4- I added connection time out in my server socket
with all my attempts I always get this error
Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at DateClient.main(DateClient.java:13)
note that DateClient.java:13 is this line Socket s = new Socket(serverAddress, 6780);
please help me with this problem , thanks in advance
I tried running your code. First, localhost (127.0.0.1) could solve your problem. On the other side, I changed the ports and IP to my own, and it just works fine (even my external IP). So probably there is something wrong with your port/IP.
In case it works using localhost, your IP was not the right one, or something on your computer is blocking external connections.
Your client code should look like this, for some reason new Socket(String host, int port) wont work.
public class DateClient {
/** Runs the client as an application. First it displays a dialog box asking for the IP address or hostname of a host running the date server, then connects to it and displays the date that it serves. */
public static void main(String[] args) throws IOException {
//I used my serverAddress is my external ip address
InetAddress serverAddress = InetAddress.getByName(String host);
Socket s = new Socket(serverAddress, 6780);
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
JOptionPane.showMessageDialog(null, answer);
System.exit(0);
}
}
If it doesn't work using localhost, your port is not forwarded correctly. Try to log in to your router and forward the port from there.
And indeed, like #Audrius Meškauskas said, you might want to close your PrintWriter on your server, right before closing your ServerSockect listener.
Close the PrintWriter on the server side
Be sure you use localhost (try 127.0.0.1) as the server address. Depending on how are you connecting the Internet, the external Internet address (as shown by various "get my ip" tools on the web) may be different from the actual address to that your network interface is configured and not work from the same machine. More here.

How to kill open server sockets under windows7?

I wrote a simple server client socket program and when I recompile the server I get:
java.net.BindException: Address already in use: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(Unknown Source)
at java.net.AbstractPlainSocketImpl.bind(Unknown Source)
at java.net.PlainSocketImpl.bind(Unknown Source)
at java.net.ServerSocket.bind(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
Therefore my question is how to kill the socket under windows 7? Is there a possible solution to kill it in eclipse?
I appreciate your answer!!
Kill the jvm this fixed the issue when I ran into it. Are you closing the socket in your code before you stop your simple server?
Like RGdev I assume that you still have a javaw process running in the background which keeps the connection open. But it could also be a different server program on your machine which hogs the port you want to use.
You can find out which processes are listening to which port with the netstat command in the cmd shell. The following parameters list (a) all connections including servers, (b) shows the executable which opened the connection and (n) suppresses the substitution of port numbers with service names for well-known ports.
netstat -abn
Here is my code for server side:
import java.io.*;
import java.net.*;
public class ServerSide {
public static void main(String[] args) {
try
{
ServerSocket myServerSocket = new ServerSocket(9999);
System.out.println("Server is waiting on host" + InetAddress.getLocalHost().getCanonicalHostName() + "port= "+ myServerSocket.getLocalPort());
Socket skt = myServerSocket.accept();
BufferedReader myInput = new BufferedReader(new InputStreamReader(skt.getInputStream()));
PrintStream myOutput = new PrintStream(skt.getOutputStream());
String buf = myInput.readLine();
System.out.println("Server readLine");
if(buf!=null)
{
System.out.println("Buf = " + buf);
myOutput.print("Got it?");
}
else
{
System.out.println("Nothing returned in server sidex`x ");
}
skt.close();
System.out.println("Server shutdown");
}
catch(IOException e)
{
e.printStackTrace();
System.out.println("Whooops");
}
}
}
As you can see for clean-up I've written:
skt.close();
But maybe this is not your problem, Maybe your problem is which I had 1 hour ago ;) I used to run a program but the result is not what I expected so I modify it and run it again but the port was busy or already in use! What I do on eclipse? Under the Console where you get the error, on the right side of the window there is red colour rectangle button! It say "Terminate". If you click on that your port will be free. By the way don't forget to check the console for both(Server/Client) sides.
You can also get this error message, when the process already terminated. TCP has a time wait state. This state is used to ensure that no TCP packets from an old connection can be delivered to a new process listening at the same port. Normally you should use the ServerSocket.setRuseAddress(true) to avoid this issue.

When is "java.io.IOException:Connection reset by peer" thrown?

ERROR GServerHandler - java.io.IOException: Connection reset by peer
java.io.IOException: Connection reset by peer
at sun.nio.ch.FileDispatcher.read0(Native Method)
at sun.nio.ch.SocketDispatcher.read(Unknown Source)
at sun.nio.ch.IOUtil.readIntoNativeBuffer(Unknown Source)
at sun.nio.ch.IOUtil.read(Unknown Source)
at sun.nio.ch.SocketChannelImpl.read(Unknown Source)
at org.jboss.netty.channel.socket.nio.NioWorker.read(NioWorker.java:323)
at org.jboss.netty.channel.socket.nio.NioWorker.processSelectedKeys(NioWorker.java:282)
at org.jboss.netty.channel.socket.nio.NioWorker.run(NioWorker.java:202)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
This log is from a game server implemented using netty. What can cause this exception ?
java.io.IOException: Connection reset by peer
The other side has abruptly aborted the connection in midst of a transaction. That can have many causes which are not controllable from the server side on. E.g. the enduser decided to shutdown the client or change the server abruptly while still interacting with your server, or the client program has crashed, or the enduser's internet connection went down, or the enduser's machine crashed, etc, etc.
To expand on BalusC's answer, any scenario where the sender continues to write after the peer has stopped reading and closed its socket will produce this exception, as will the peer closing while it still had unread data in its own socket receive buffer. In other words, an application protocol error. For example, if you write something to the peer that the peer doesn't understand, and then it closes its socket in protest, and you then continue to write, the peer's TCP stack will issue an RST, which results in this exception and message at the sender.
java.io.IOException in Netty means your game server tries to send data to a client, but that client has closed connection to your server.
And that exception is not the only one! There're several others. See BadClientSilencer in Xitrum. I had to add that to prevent those errors from messing my log file.
java.io.IOException: Connection reset by peer
In my case, the problem was with PUT requests (GET and POST were passing successfully).
Communication went through VPN tunnel and ssh connection. And there was a firewall with default restrictions on PUT requests... PUT requests haven't been passing throughout, to the server...
Problem was solved after exception was added to the firewall for my IP address.
For me useful code witch help me was http://rox-xmlrpc.sourceforge.net/niotut/src/NioServer.java
// The remote forcibly closed the connection, cancel
// the selection key and close the channel.
private void read(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
// Clear out our read buffer so it's ready for new data
this.readBuffer.clear();
// Attempt to read off the channel
int numRead;
try {
numRead = socketChannel.read(this.readBuffer);
} catch (IOException e) {
// The remote forcibly closed the connection, cancel
// the selection key and close the channel.
key.cancel();
socketChannel.close();
return;
}
if (numRead == -1) {
// Remote entity shut the socket down cleanly. Do the
// same from our end and cancel the channel.
key.channel().close();
key.cancel();
return;
}
...
There are lot of factors , first see whether server returns the result, then check between server and client.
rectify them from server side first,then check the writing condition between server and client !
server side rectify the time outs between the datalayer and server
from client side rectify the time out and number of available connections !
It can also mean that the server is completely inaccessible - I was getting this when trying to hit a server that was offline
My client was configured to connect to localhost:3000, but no server was running on that port.

Java socket blocks on connection to a server

I am trying to connect to server using a Java socket. I am trying to connect from port 80 to 90
int port;
Socket clientsocket;
String hostname = "www.google.com";
for(port = 80;port<=90; port++){
try{
clientsocket = new Socket(hostname,port);
System.out.println("Connection at port " + port + "\t" + clientsocket.isConnected());
clientsocket.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
When I try to connect to any website like google.com or w3schools.com my program hangs on the socket() call for port numbers except 80.
Since those websites are not serving on ports 81-90 it should raise exception but instead it gets blocked. For port 80 it works fine.
When I try to connect to the apache server installed on my machine, it doesn't block for any port number and gives me Connection refused error which is the obvious behavior.
So why is it happening. Thanks in advance.
When I try to connect to any website like google.com or w3schools.com my program hangs on the socket() call for port numbers except 80. Since those websites are not serving on ports 81-90 it should raise exception but instead it gets blocked.
This is almost certainly not Java's doing.
When you invoke the Socket(String, int) constructor, the JVM asks the OS to attempt to establish a connection to the IP address corresponding to the supplied name, using the supplied port number. Assuming that we're talking TCP/IP, the OS sends off a TCP 'SYN' message, and waits for a response:
If the response is a 'SYN-ACK', it proceeds to establish the connection as per the protocol; see http://en.wikipedia.org/wiki/Transmission_Control_Protocol#Connection_establishment.
If the response is an 'RST' (reset), the connect fails and this results in a Java "connection refused" exception. (This is typically what happens if the 'SYN' makes it to the remote server, only to discover that there is no application "listening" on the port you tried to connect on.)
If the response is an ICMP message of some kind (e.g. ICMP destination unreachable), this typically results in an immediate failure of the connection request, and a Java exception.
If there is no response, the OS tries again, and again, and again. Depending on the Java default connect timeout (or the explicit timeout), this process could continue for a long time.
So what is most likely happening is that something is filtering the 'SYN' messages on funky ports, and simply throwing them away. It could be the local firewall software on your PC, firewall software in your gateway, or your ISP's network, or software in the remote system you are attempting to talk to. Or this could be happening to the 'SYN-ACK' message coming back.
Either way, the blocking / timeout behavior is inherent to TCP/IP networking, and it is impossible to accurately diagnose at either the OS or Java levels. You simply need to adjust your expectations. (Or set a shorter connect timeout ...)
For this case, and any case:
/**
* Create end point and initialize connection with custom timeout for refused or server offline
*/
try{
InetSocketAddress endPoint = new InetSocketAddress(serverAddress, portNumber);
Socket socket = new Socket();
socket.connect(endPoint, 10000);
} catch(Exception e){
//... Handle connection error
}

Categories