How to associate (outgoing, of course) HttpUrlConnection with a specific local IP address when I have several network adapters on my client machine?

I have a kind of Http-Gateway application that acts as an http client to servers outside our local network.

There will be a network configuration update, and I will have problems because:
- there are several network cards on the client machine
- firewall / nat rules use hard IP addresses

If I could programmatically force the HttpUrlConnection object to use a specific IP address, I would be fine. But I am afraid that this is impossible.

I'm right? If not, which version of the JRE supports it?

Other possible solutions, preferably those not related to rewriting everything from scratch?
The simpler the better: I know there is Apache HttpClient, or I can use Sockets ...

thanks

+2
java networking
source share
3 answers

I do not see a good solution, but I have two bad possibilities:

  • Proxy local connections:

    Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress( "proxy", 5555)); URLConnection urlConnection = url.openConnection(proxy); 
  • Register your custom URLStreamHandlerFactory with java.net.URL . Whenever openConnection() is called on a URL , it is processed by this registered custom factory, giving you control over the details of the socket connection. Or use an Apache implementation or collapse your own?

     Url.setURLStreamHandlerFactory(URLStreamHandlerFactory fac) 
+3
source

You can not. HttpURLConnection does not provide any interface for socket management.

You should not do that either. The choice of interface is based on a routing solution. If you need to manually select a network adapter to get to your destination, all your internet connection will have the same problem. You must add a static route to the OS to ensure that the destination is using the correct interface.

+2
source

There is a constructor for the Socket class ( http://java.sun.com/j2se/1.4.2/docs/api/java/net/Socket.html ) that allows you to specify localAddr. This allows you to do what you want in Java.

Unfortunately, the HttpUrlConnection and its class family do not give you much opportunity to get a base socket. I followed the possibilities offered by setContentHandlerFactory , but this allows you to control the content only after opening the socket.

Thus, my suggestion would be to turn the administrator’s hand in the direction of changing the routing table of your computer so that the only possible (or optimal) route from this computer to the target hosts passes through the gateway that you want to use, Thus, when the connection the socket will be open, it will be the default for the card for this gateway.

0
source

All Articles