Can I specify *source* IP address for a JDBC connection?

Tags: , , ,



I have a Java application that connects to a database with a JDBC driver. It happens to be a Postgres instance, but I’m looking for a general solution if it exist.

The server on which the application runs has multiple IP address, all in the same subnet. The JDBC connection is established using the ‘primary’ IP of the server.

I can play with Linux networking stack to have outgoing connections to the database use the secondary IP address.

Is there a way to programatically specify the source IP address will be used to to my JDBC connection?


Context: We want to move the application without touching the database, which has rules restricting IP address it will accept connections from.

The only hack I see would be making an SSL connection, and return a new Socket bound to the secondary IP from a custom SSLSocketFactory.

Answer

Some googling suggests that it depends on a particular JDBC driver.

For MySQL, it’s done via property on the URL:

jdbc:mysql://localhost:3306/sakila?localSocketAddress=123.33.33.33

(See https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-configuration-properties.html)

In the case of Postgres, looks like your best option is socketFactory URL property – just create plain old sockets, not SSL sockets.

(See https://jdbc.postgresql.org/documentation/head/connect.html#connection-parameters)



Source: stackoverflow