Skip to content

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

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.



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

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



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