3

I have a Java application that needs to connect to a remote PostgreSQL database over a VPN. Here is the relevant code:

Class.forName("org.postgresql.Driver");
Connection con = null;
con = DriverManager.getConnection("jdbc:postgresql://" + sqlHost + ":" + sqlPort + "/mydb", username, password);

This throws the error

org.postgresql.util.PSQLException: FATAL: pg_hba.conf rejects connection for host "172.16.7.5", user "xxxxx", database "xxxxx", SSL off

The Host IP address in sqlHost is actually 192.168.12.55, but if you notice the error message says that it is connecting to host 172.16.7.5 (which is the IP address assigned by the VPN).

I am able to connect to this PostgreSQL database using the exact same connection parameters on the exact same VPN using PGAdmin and using Python's psocopg2 module. Here is the equivalent Python code:

conn = psycopg2.connect("dbname=mydb user="+username+" password="+password+" host="+sqlHost+" port="+sqlPort)

Why in the world is only Java having problems with this? Since the connection works over PGAdmin and Python, I assume there is some setting in Java that I am using incorrectly, but I can't find anything.

EDIT: After reading into PostgreSQL docs a little more, I found that the issue with it listing the wrong hostname is not part of the issue but rather just the way PostgreSQL sees my computer over the VPN. Problem is still not solved, however.

Joshua Welker
  • 547
  • 1
  • 9
  • 20
  • I believe this belongs on [su] (or maybe [sf]) – Jim Garrison Aug 08 '13 at 19:11
  • 3
    I think it is more appropriate for StackOverflow because it is related to the code of an application I am creating. I need to know if there is a special parameter in Java's SQL connection manager that allows it to properly work over a VPN. – Joshua Welker Aug 08 '13 at 19:22

2 Answers2

5

Okay, I fixed this myself. The problem had nothing to do with the VPN but rather with the fact that Java by default does not try any sort of SSL connection by default whereas PGAdmin and psycopg2 do.

The solution was to add the following parameters to my connection url: ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory

Joshua Welker
  • 547
  • 1
  • 9
  • 20
  • Good catch. You should mark this as your answer too, for the benefit of other readers who might have this problem. :) – Jason C Aug 14 '13 at 15:33
2

I'm not sure if this might be the problem, but I've experienced similar problems in the past trying to connect to a database with VPN turned on.

Try running your application with this JVM argument passed at application launch time:

-Djava.net.preferIPv4Stack=true

See also this answer for a more permanent solution.

Community
  • 1
  • 1
axiopisty
  • 4,972
  • 8
  • 44
  • 73
  • I tried both adding `-Djava.net.preferIPv4Stack=true` to eclipse.ini and also adding `System.setProperty("java.net.preferIPv4Stack" , "true")` in my code. No luck in either case. – Joshua Welker Aug 08 '13 at 19:28