My Tomcat instance is listening to multiple IP addresses, but I want to control which source IP address is used when opening a URLConnection
.
How can I specify this?
My Tomcat instance is listening to multiple IP addresses, but I want to control which source IP address is used when opening a URLConnection
.
How can I specify this?
This should do the trick:
And you are done. Dont forget to handle exceptions nicely and off course change the values to suit your scenario.
Ah and I omitted the import statements
Setting manually socket work fine ...
Using the Apache commons HttpClient I have also found the following to work (removed try/catch for clarity):
However, I still wonder what would happen if the gateway of the IP is down (192.168.1.11 in this case). Will the next gateway be tried or will it fail?
The obvious portable way would be to set a Proxy in URL.openConnection. The proxy can be in local host, you can then write a very simple proxy that binds the local address of the client socket.
If you can't modify the source where the URL is connected, you can replace the URLStreamHandler either when calling the URL constructor or globally through URL.setURLStreamHandlerFactory. The URLStreamHandler can then delegate to the default http/https handler, modifying the openConnection call.
A more extreme method would be to completely replace the handler (perhaps extending the implementation in your JRE). Alternatively, alternative (open source) http clients are available.