Search code examples
javajdbcconnection

How to get current PC name?


I am working on a project and i want to make my project portable. Connecting java and SQL server 2012 and using PC Name in the connection.In my case it is Hwl. :

Connection conn = DriverManager.getConnection("jdbc:sqlserver://localhost\\Hwl:1433;databaseName=dbs","sa","dbase");

Statement statement = conn.createStatement();

Now i want to get PC-Name (e.g Hwl in my case ) on the machine in which that code is running. I simply want to get the PC name and pass that to the connection string in each machine where it runs.


Solution

  • Following function would return hostname.

    public String getHostName() {
        String hostName = "";
        try {
            java.net.InetAddress addr = InetAddress.getLocalHost();
            hostName = addr.getHostName();
        } catch (UnknownHostException ex) {
          System.out.println("Hostname can not be resolved");
        }
        return hostName; }