开发者

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
   开发者_如何学Python     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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜