bill0ute
bill0ute

Reputation: 369

Java : Reuse Bound Socket with different IP?

I want to do something like that :

public void  myFun (String  tIps [])
{
    Socket  s = new Socket ();
    s.connect (new InetSocketAddress (serverIp, 80), 1000);

    for (int  i = 0 ; i < tIps.length ; ++i) 
    {
        // Rebind the socket with another Ip
        s.bind (new InetSocketAddress (tIps [i], 0));

        /*
        *   use the socket
        */
    }

    s.close ()
}

But I get this error : "java.net.SocketException: Already bound". I tried to use s.setReuseAddress (true), but it did'nt change anything. Is there any solution to avoid opening a new socket for each request, which is very long ?

Thanks !

Upvotes: 1

Views: 771

Answers (2)

user207421
user207421

Reputation: 310916

That's not what bind() is for either. The socket is already connected to a target: what would be the point of changing the local outbound interface after that?

Just omit the bind step altogether. The routing tables will figure out which local interface to use to connect to the target.

Upvotes: 0

bmargulies
bmargulies

Reputation: 100040

That's not what setReuseAddress is for. That function corresponds to the classic SO_REUSEADDR, which is related to re-using a port that some other process has been listening on recently.

There is no way in Java to do what you want.

Upvotes: 1

Related Questions