user2689005
user2689005

Reputation: 11

Set local bind address for client socket in java

I have multiple NIC (Network interfaces) installed on a server. Is it possible for me to set the default local bind address for existing client sockets in JAVA?

It is possible to do it programmatically through the method:

new Socket(InetAddress address, int port, InetAddress localAddr, int localPort)

Problem is that I don't have access to SocketFactory so I cannot specify localAddr value.

Upvotes: 1

Views: 4324

Answers (1)

Robadob
Robadob

Reputation: 5349

The documentation of the abstract SocketFactory.createSocket() method you speak of in your question, points to this constructor that offers what you need;

 public Socket.Socket(InetAddress address,
     int port,
     InetAddress localAddr,
     int localPort)
         throws IOException

Docs found here


If you need to change the localAddress of an existing socket you should use the bind(SocketAddress bindpoint) method, however that will throw an IOException if the socket is already bound.

You should pass an InetSocketAddress to that method as SocketAddress is abstract.


If your having trouble finding the internal IP addresses of each of your interfaces this guide explains how to retrieve a collection of them.

Upvotes: 1

Related Questions