简体   繁体   中英

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 !

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM