File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Sockets and Internet Protocols and the fly likes Connecting Sockets thru Proxy Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Sockets and Internet Protocols
Bookmark "Connecting Sockets thru Proxy" Watch "Connecting Sockets thru Proxy" New topic

Connecting Sockets thru Proxy

Gopal Shah
Ranch Hand

Joined: May 17, 2003
Posts: 65
Hi All,
I am trying to make socket connections thru a local firewall, for which I am setting the proxy host and port num.
I tried the method described in the following link
Getting through a Proxy with Sockets
But somehow I was unsuccessful to do so. Using the URLConnection approach it works i.e. when I do the

or its equivalent mentioned in link above.
But for sockets it doesn't work, although I am trying to connect to the http port only. I even tried reading the source code of URL and its related classes -> URLConnection, etc. but it looks like URLConnection doesn't use the socket abstraction (Socket class in Java) and instead uses native methods to connect thru OS level sockets. Correct me if I am wrong in my understanding.
In Java API doc, its written
An application, by changing the socket factory that creates the socket implementation, can configure itself to create sockets appropriate to the local firewall.

Will this method work ? If yes how do we write custom socket factory ?
Thanks and regards,
Marlene Miller
Ranch Hand

Joined: Mar 05, 2003
Posts: 1391
I have a guess as to why Socket(host, port) fails with Connection refused. Does this make sense?
This is how I see the problem:
This works:
URL u = new URL(;
URLConnection uc = u.openConnection();

But this does not work:
InetAddress addr = new InetAddress(;
Socket s = new (addr, 80);
This is the exception: Connection refused: connect
When I do this:
URL u = new URL(host);
URLConnection uc = u.openConnection();
I get this:
Here is my explanation. Does this make sense? is a subclass of the abstract class URLConnection. Sun must implement the abstract method URLConnection.connect().
I am guessing, when Sun implements connect(), Sun is calling Socket(host, port) with host and port of the proxy server. Sun is negotiating with the proxy server using the HTTP protocol.
[ March 03, 2004: Message edited by: Marlene Miller ]
I agree. Here's the link:
subject: Connecting Sockets thru Proxy
It's not a secret anymore!