Oli Oli - 3 months ago 13
HTTP Question

Very confusing case: "java.net.ConnectException: Connection refused" by some hosts (one time this exception, one time not!)

I have a totally normal class in Java for HTTP Connection to get a HTTP responce headers from a Server. I seems to be absolut okay, and it is actually works fine for the most of the web-sites that I've tested. But..

import java.net.HttpURLConnection;
import java.net.URL;
public class Main2 {
public static void main(String[] args) {
HttpURLConnection con = null;
try {
URL url = new URL("http://sometestsite.blabla/");
con = (HttpURLConnection) url.openConnection();

} catch (Exception e) {

BUT there are some sites, and by testing of them with this class, I get one time "java.net.ConnectException: Connection refused" Exception and secound time ... it works fine (by the same hostname) and I get an answer! And it goes so on and so on. One time an answer one time an exception.


java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:432)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:527)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:211)
at sun.net.www.http.HttpClient.New(HttpClient.java:308)
at sun.net.www.http.HttpClient.New(HttpClient.java:326)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1169)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1105)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:999)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:933)
at Main2.main(Main2.java:14)

When I test the same hostname in Browser, I become always an answer. When I test the same hostname in curl (ubuntu), i get always an answer either (so in both cases no exceptions).

I'm really confused, please write if you have any ideas. Thanks a lot!

Oli Oli

Now I can give an answer with information from my last comment:

Wireshark gave me a hint, by connections with source port > 45000 the connection will be accepted, by smaller ports not.By first connection Java choosed source port 36846 and by secound one 45852, so the secound one passes The curl also used 2 trys: one with a smaller port and one with a bigger (> 51000) so that passes too. The browser uses the first time port > 45000.

Result: seems to be a missconfigured firefall.