I'm trying to program a (simple, for starters) server-client thingy, just to establish a connection and see if it works. And it does. As long as I stay inside my own four walls/network. As soon as I try to go via my routers IP the client produces a mighty fine error message. All the usual suspects have been eliminated: Router Port forwarding is on, the firewall doesn't interfere (well, it still doesn't work when I turn it off), and canyouseeme.org says that it can establish a connection to my chosen port when the server runs.
Here is the source code for the server, since I figured out it was possible to just go via the command line with a little telnetting.
When I try to establish a connection, it just says Could not open connection to the host, on port 49163:Connection failed
Server:
import java.net.*;
import java.io.*;
public class ChatServer {
public static void main(String[] args) throws IOException {
ServerSocket server = null;
try {
System.setProperty("java.net.preferIPv4Stack" , "true");
server = new ServerSocket(49163);
} catch (IOException e) {
System.err.println("Could not listen on port: 49163.");
System.exit(1);
}
Socket client = null;
try {
client = server.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
BufferedReader in = new BufferedReader(newInputStreamReader(client.getInputStream()));
String inputLine;
String outputLine;
out.println("Connection established");
while ((inputLine = in.readLine()) != null) {
if (inputLine.equals("exit")) {
break;
}
outputLine = inputLine;
out.println(outputLine);
}
out.close();
in.close();
client.close();
server.close();
System.out.println("Server offline");
}
}
Oh yeah, preferIP4vStack was something I picked up on Stackoverflow, but it doesn't seem to work for me.
For some reason I'm not able to inlcude the code for the client, I keep getting messages about formatting, and I just can't figure it out. But the way I see it is that I'm not even able to connect via the command line (when I try to connect to the "real" IP), so the client doesn't have to get involved. But for you who want to see the error anyway:
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(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 ChatClient.main(ChatClient.java:12)
Could not open connection to the host, on port 49163:Connection failed
No it didn't. Thats not a Java message. Your code said that, when you caught a ConnectException that had a much more detailed message of its own. Print that and you might have some hope of finding what went wrong. Making up your own messages and suppressing what the exception tells you is rarely if ever a good idea.
The message will probably be one of:
'connection refused', which means you got the target host or port wrong, or there is a firewall
'connection timed out', which is a network connectivity problem
'no route to host', which is an IP routing problem
'unknown host', which again means you got the server name wrong.
I don't know if I'm suposed to laugh or cry now.
A friend told me that MAYBE, maybe the problem might be that I try to log in with the external IP from a network-intern PC, which for some mysterious reason can't get out or can't get back in.
Got someone to try and login from somewhere else, and voila! Works like a charm.
Related
We've many servers which host multiple IP addresses. The additional ones are so-called Virtual IPs ("VIPs").
We'd like to enable a Java app to make an outgoing connection which lists as source address a designated Virtual IP rather than the host ip address.
Here's what we've tried. The ip address listed in InetAddress#getByAddress is the virtual ip address. The property url is a user-specified target url to connect to.
public void attemptConnection() {
try {
Proxy proxy = new Proxy(Proxy.Type.HTTP,
new InetSocketAddress(InetAddress.getByAddress(new byte[]{(byte)10,(byte)252,(byte)47,(byte)33}), 0));
final URL _url = new URL(url);
final URLConnection conn = _url.openConnection(proxy);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
The code above was modelled on this answer
We're testing this with Python's SimpleHTTPServer, simply running python -m SimpleHTTPServer then trying to connect.
If we use no proxy in our Java code then the connection works correctly.
However, as soon as the VIP proxy is defined we get connection refused:
java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:327)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:193)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:180)
at java.net.Socket.connect(Socket.java:546)
at java.net.Socket.connect(Socket.java:495)
at sun.net.NetworkClient.doConnect(NetworkClient.java:178)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:409)
at sun.net.www.http.HttpClient$2.run(HttpClient.java:457)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.http.HttpClient.privilegedOpenServer(HttpClient.java:454)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:521)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:240)
at sun.net.www.http.HttpClient.New(HttpClient.java:321)
at sun.net.www.http.HttpClient.New(HttpClient.java:338)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:935)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:914)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:801)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1139)
at com.ocado.dsi.ConnectToUrl.attemptConnection(ConnectToUrl.java:38)
at com.ocado.dsi.ConnectToUrl.run(ConnectToUrl.java:56)
at com.ocado.dsi.ConnectToUrl.main(ConnectToUrl.java:64)
Any ideas why?
Update
When specifying the local address on a socket directly the process works fine.
I setup a Python simple socket server listening on port 8000 just as the SimpleHTTPServer used above does. Connecting to this from Java using a socket with the desired local address worked as expected: the python server recognised the incoming connection source address as that defined by the user.
Socket s = new Socket(InetAddress.getByAddress(new byte[]{(byte)10,(byte)252,(byte)47,(byte)33}), 8000, InetAddress.getByAddress(new byte[]{(byte)10,(byte)97,(byte)5,(byte)147}), 0);
s.close();
I'm going to dig into Socket#setSocketImplFactory to see whether the problem can be resolved by customising every created socket.
The problem is that both Socket#setSocketImplFactory and URL.setURLStreamHandlerFactory enable you to override the default implementation but do not give you access to the default implementation, so they seem to be very much all-or-nothing overrides. This is very annoying when you only wish tor add logic on top.
FTPClient client = new FTPClient();
FileInputStream fis = null;
try {
client.connect("32.178.10.121");
client.login("XXX", "XXX");
//
// Create an InputStream of the file to be uploaded
//
String filename = "Touch.dat";
fis = new FileInputStream(filename);
//
// Store file to server
//
client.storeFile(filename, fis);
client.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
client.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
I have tried this but each time it gives time out of bound exception and by other means of i am successfully getting connected but nt from here what could be reason.
this is the stacktrace:
java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(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 org.apache.commons.net.DefaultSocketFactory.createSocket(DefaultSocketFactory.java:53)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:162)
at org.apache.commons.net.SocketClient.connect(SocketClient.java:250)
at forTesting.FileUploadDemo.main(FileUploadDemo.java:15)
First try to set the proxy details like below
FTPClient ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword);
Then try to connect as you are doing and let me know if the error is gone.
If the error persists then check the firewall setting for the FTP server. Also try to connect from the System with some GUI tool like Filezilla to connect to the server.
You might want to try using PASV mode, if you're behind a firewall or proxy. Have a look here:
In situations where the client is behind a firewall and unable to
accept incoming TCP connections, passive mode may be used. In this
mode, the client uses the control connection to send a PASV command to
the server and then receives a server IP address and server port
number from the server, which the client then uses to open a
data connection from an arbitrary client port to the server IP address
and server port number received.
I have encountered the following error:
java.net.ConnectException: Connection refused: connect
I'll show some code below but first, a description because it baffles me. I wrote a very basic chat program that can act as either a server or client depending on the initial button you press (host or connect). Tested on both localhost and over the internet with friends, works perfectly, as intended. I've started writing a second software and using almost the same code, but having more classes, I get this error when trying to connect to a host of the same program. So, prog A can connect to prog A fine, but B cannot connect to B. One might assume firewall issues, but here's the plot twist: B can connect to A and A can connect to B again perfectly. But B cannot connect to another copy of itself. I used the official oracle tutorials for TCP and worked perfectly on the chat program referred to as A. Depending on the press of a button, A will run one of its main class' methods (to start a server or client). B on the other hand, will create a new object of a class, either a Host
public class Host
{
static ServerSocket serverSocket = null;
static Socket clientSocket = null;
static PrintWriter out = null;
static BufferedReader in = null;
static String inputLine;
public Host() throws IOException
{
serverSocket = new ServerSocket(4444);
System.out.println("Server created, waiting for guest.");
clientSocket = serverSocket.accept();
System.out.println("Guest connected.");
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
while ((inputLine = in.readLine()) != null)
{
//if (inputLine.equals("q")) {break;}
System.out.println("Message recieved:" + inputLine);
}
}
}
or a Guest
public class Guest
{
static Socket socket = null;
static PrintWriter out;
static BufferedReader in = null;
static String inputLine;
public Guest() throws IOException
{
System.out.println("Connecting to host");
try
{socket = new Socket("localhost", 4444);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
catch (UnknownHostException err) {System.out.println("unknown host"); System.exit(3);}
catch (IOException err) {System.out.println(err); /*System.exit(4);*/}
System.out.println("Connected to host");
while ((inputLine = in.readLine()) != null)
{
//if (inputLine.equals("q")) {break;}
System.out.println("Message recieved:" + inputLine);
}
}
}
I have the proper imports, I just didn't paste them here. Both programs try to connect to localhost and only A works, this other one does not. Again, creating a Guest, I can connect to the chatprogram's server. A chatprogram client can connect to this server. But this client cannot connect to this server.
Has anyone experienced anything similar? Is there an obvious solution, something I'm missing? I'm really clueless here, I literally copy/pasted server/client codes.
Edit: stack trace.
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
java.net.ConnectException: Connection refused: connect
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 mainPack.Guest.<init>(Guest.java:21)
at mainPack.GameStarter.grandMain(GameStarter.java:101)
at mainPack.GameStarter.<init>(GameStarter.java:27)
at mainPack.GameStarter.main(GameStarter.java:34)
In your Host, you only accept one connection, and then the server stops listening. If something is tying up that connection, nothing else would be able to connect to the Host. An accepted connection should immediately be delegated to another thread for processing so that the Host can loop and listen on the server socket again. See "Supporting Multiple Clients" in the Socket tutorial.
Remove your static declarations from the variables in Guest. Same for Host (although if you have only one host it should be ok).
Update
e.g. pseudo-code
create server socket
while true (or quit received) {
accept connection
spawn thread to handle communication
}
Need more details as to how this is being run and what the error is exactly (I suspect client returns a network-level connect error when attempting to reach the host) but in general there is only one port being used: 4444. I presume the error (not posted) is that this port is in use by the first programs that are communicating on that port on the same machine.
Further, the static references only allow one instance of the various sockets to exist in a given JVM at a time. These cannot be concurrently used by multiple threads possibly implemented by other client classes using these same (one) static resources.
I've created a chat program which required the user to select either the client or server role. My approach at removing this requirement is to have every user start their own server where they'll get messages from. This should allow me to have two clients talk to the the other without having to put a server in between them.
Right now I've modified my program in such a way that the client side does the sending and the server does the receiving.
Note that communication between the two programs worked perfectly fine up untill these changes. However, now that I've changed some stuff an error occurs as early as when I create a socket.
The flow of my program untill the problem is as follows:
Program starts
Server starts automatically, binded to local port 6666
Connection config pops up, user clicks the save button (target host and port are saved)
User clicks the connect button
Program creates a client thread
Thread creates the socket and initiates the outbound stream
After some debugging I've found that this socket is never created.
When the flow enters this stage (last item in the list), only the 'First test' gets executed.
public void run() {
System.out.println("First test");
createConnection();
System.out.println("Second test");
initiateIO();
}
private void createConnection() {
try {
socket = new Socket(host, port);
} catch (UnknownHostException e) {
OutputUtil.showErrorMessage("Couldn't bind socket to unknown host", "Unknown host");
} catch (IOException e) {
OutputUtil.showErrorMessage("General IO error at creating client socket", "IO error");
}
}
private void initiateIO() {
try {
outbound = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
OutputUtil.showErrorMessage("Couldn't load IO streams from client", "IO Error");
}
}
Output:
Console: First test
Popup: General IO error at creating client socket
Console: Second test
Console: NPE at `outbound.close()`
I'm assuming the NPE is a result of the first error, considering a method from the socket is invoked when creating the PrintWriter. It should also be noted that it takes around 10 seconds to show the first error.
At first I thought the error might be introduced because both the local server and the connection with the other client use port 6666, but after creating a link on port 6667 the problem still occurred. Which makes sense upon review.
When my debugger points at the line where outbound is initialized (after the "second test" message, socket has value null.
My question is: why can't the socket be created? The documentation only specifies
IOException - if an I/O error occurs when creating the socket.
which isn't of much use.
Full source code can be found here for a better overview.
Edit: Printed the stacktrace from the first, main error.
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 core.Client.createConnection(Client.java:30)
at core.Client.run(Client.java:64)
at java.lang.Thread.run(Unknown Source)
This is a firewall problem. The target port you specified wasn't open in the target's firewall.
The server may also not have been running, but if that was the only problem it would have been 'connection refused', not 'connection timed out: connect'.
I've seen few threads about this topic but I still can't figure out what's wrong. Following is the code:
import java.sql.*;
public class SQL
{
public static void main(String[] args)
{
Connection conn = null;
String url = "jdbc:mysql://mysql1.oyo.co.il:3306/";
String dbName = "sdarot2_winner";
String driver = "com.mysql.jdbc.Driver";
String userName = "";
String password = "";
String table = "LEADER_CAM_PRODUCTS";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
}catch (Exception e) {
System.out.println(e);
}
}
}
And here is the error I get:
com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying > > exception:
** BEGIN NESTED EXCEPTION **
java.net.ConnectException
MESSAGE: Connection timed out: connect
STACKTRACE:
java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(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.(Unknown Source)
at java.net.Socket.(Unknown Source)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
at com.mysql.jdbc.MysqlIO.(MysqlIO.java:271)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:2744)
at com.mysql.jdbc.Connection.(Connection.java:1553)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at SQL.main(SQL.java:17)
** END NESTED EXCEPTION **
Last packet sent to the server was 1 ms ago.
Here is few things I found around:
The I.P/domain or port is incorrect
The I.P/domain or port (i.e service) is down
The I.P/domain is taking longer than your default timeout to respond
You have a firewall that is blocking requests or responses on whatever port you are using
You have a firewall that is blocking requests to that particular host
Your internet access is down
a) it is correct.
b) it's not down since I got a website that is working right now with that database.
c) how can I check that?I don't think that it's the problem since as I said I got a running website on this database.
d) now way because the same reason I mentioned above.
e) samem as d
So what I'm doing wrong?how come a php code can work with sql but java gives me errors?
Thank you.
As an experiment, try connecting to port 3306 on mysql1.oyo.co.il using your system's telnet command. Or some other utility (for example nc or netcat) that opens a raw TCP/IP connection. Depending on your OS / distro, you may have to locate and install a suitable command to help you with this trouble-shooting. Observe what happens.
Re your diagnosis:
a) it is correct.
If you say so ...
b) it's not down since I got a website that is working right now with that database.
At best you have demonstrated that the host is working. The web service on port 80 and the MySQL service on port 3306 are different services. (And in fact, it is possible that mysql1.oyo.co.il is doing clever packet routing tricks so that traffic on different ports is being tranparently routed to different hosts or virtual hosts.)
c) how can I check that?
Try changing / increasing the timeout.
I don't think that it's the problem since as I said I got a running website on this database.
My guess it is not a timeout issue ... but as I said above, the fact you got a website says NOTHING about whether the MySQL service is running.
d) now way because the same reason I mentioned above.
You've only demonstrated that you can get to port 80 ... see above
e) samem as d
You've only demonstrated that you can get to port 80 ... see above
Based on the above, it is plausible that:
you have a local firewall problem,
the MySQL service on that port is not currently running,
networking routing on the service side are broken for traffic on that port,
the MySQL service has been permanently turned off, or
the service's firewall has been configured to not accept network connections from random (or specific) places, including yours.
The fact that you are seeing a timeout rather than a "connection refused" suggests that this is more likely to be a networking or firewalling issue than a problem with the MySQL service endpoint itself.
My guess is that "they" have withdrawn the service ... and that you are not supposed to use it anymore. (Providing a public MySQL database service strikes me as an odd thing to do ... as well as being problematic from a security and administration standpoint.)
'Connection timed out' indicates either:
a server-side firewall that is deliberately ignoring your connection request
a network topology problem such that IP packets aren't getting through
the server host itself is down.
Most likely it is the first.
Note that, contrary to other answers here, it doesn't indicate that the server program is down, or a local firewall problem at the client. The former would cause 'connection refused' and the latter would give you something along the lines of 'permission denied', depending on your platform.