Getting db hostname and port number from a jdbc connection

I have a connection like this.
    DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
         conn = DriverManager.getConnection(
            "jdbc:oracle:thin:@devbox:1521:UTF", "test", "test");

and I want to find out the following information from the connection.   I can get some of the information I need, but not all of it and the javadocs are not much help getting this out.  I've looked at INetAddress, but this seems to give local hostnames, not the hostname and the port number of the database I am connected to.
   try {
        DatabaseMetadata metaData = conn.getMetaData();
        String URL metaData.getURL();
        String hostname = /* How do we do this? */
        int port = /* how do we do this? */
        String DBType = metaData.getDatabaseProductName();
        String username = metaData.getUserName();
       } catch (SQLException e) {
Who is Participating?
Mayank SConnect With a Mentor Associate Director - Product EngineeringCommented:
Yes but that would work only for Oracle, not for other DBs - there is no generic way to do this, unless you want to get your hands dirty with it and just parse the connection string/ URL to obtain the values (but again, the values will be in a different format in the connection-string depending on the DB/ driver).
The hostname and port are in the connection string:

hostname: devbox
port: 1521
Check this

Looks like you can use

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

BarryMcGillinAuthor Commented:
These dont seem to work.  I'm wondering why this doesn't work either.
If we get back a URL, surely then creating a standard will be able to pull it out.
 try {
           connURL = new URL(metaData.getURL());
      } catch (MalformedURLException e) {
       String host = connURL.getHost();
       int port = connURL.getPort());
Unfortunately I'm getting this.....
<exception> unknown protocol: jdbc
Mayank SAssociate Director - Product EngineeringCommented: is not for JDBC URLs. It is for web-like URLs that are on HTTP, etc.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.