Socket Binding at URL.openconnection()

Viewed 143

JRE 8\

How do I select the IP address FROM which this request will be fired? Server has multiple IP addresses bind to it, multiple interfaces. I want to use a specific one for this request.

I have httpsurlconnection.

URL url = new Url("x");
HttpsUrlConnection connection = (HttpsUrlConnection) url.openConnection();
...
connection.setSSLSocketFactory(SSLSocketFactory);
connection.connect();

I overrided in SSLSocketFactory all createSocket with binding source ip to choosen by me. Problem is when I:

URL url = new Url("x");
HttpsUrlConnection connection = (HttpsUrlConnection) url.openConnection();
...
connection.setSSLSocketFactory(SSLSocketFactory);
connection.connect();

I see that socket is created and my sslsocketfactory using createSocket with created socket. I can bind then to other ip address but I want to override source IP address when openConnection. Where can I override it?

1 Answers
HttpsUrlConnection

using

SSLSocketFactory.createSocket();

Override this with something like

Factory extends SSLSocketFactory{
    private SSLSocketFactory basicFactory;

    Factory(SSLSocketFactory basicFactory){
        this.basicFactory = basicFactory;
    }
...
    @Override
    public Socket createSocket() throws IOException {
        Socket socket = basicFactory.createSocket();
        socket.bind(sourceIpAddress);
        return socket;
    }
}

Don't use super.createSocket() because it will throw SocketException("Unconnected sockets not implemented") which will be caught in HttpsClient and use NetworkClient to create socket with java.net.Socket with random source ip address

Related