Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing socket underlying URL connection in Java

I have a Java application that uses java.net.URL to open a location to retrieve some data. I now have the requirement to open the connection via VPN. The Linux machine it runs on, now can have a number of tunnels open at any one time, and I need to be able to programmatically tell the application which tunnel to use.

I believe that using java.net.Socket it's possible to choose the virtual device to open the connection on, but I could not find any way to overlay the URL object to handle all the HTTP traffic - or replace the underlying socket before actually opening the connection.

So, how do I connect my application to a particular network interface and keep the advantage of using a high-level object like java.net.URL?

Now, I am not sure if this is possible at all, but I thought I'd ask the wise stackoverflow community...

like image 988
Alberto Giannetto Avatar asked Jan 19 '26 09:01

Alberto Giannetto


1 Answers

I believe you can register a custom URLStreamHandlerFactory with java.net.URL. Whenever openConnection() is called on the URL it would be handled by this registered custom factory, giving you control over details of the socket connection.

Once you have the ability to manipulate socket creation, specifying the network interface you use is fairly trivial:

NetworkInterface ni = NetworkInterface.getByName("eth0");
Socket socket = new Socket();
socket.bind(ni.getInetAddresses().nextElement());

It looks like there are a few libraries out there that provide simple access for setting the socketFactory used by an HTTP connection. See for example http://faban.org/1.1/docs/api/index.html?com/sun/faban/driver/transport/sunhttp/HttpURLConnection.html

like image 128
mflaming Avatar answered Jan 21 '26 23:01

mflaming



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!