Java Host Name Get getHostName()

Here you can find the source of getHostName()

Description

Returns the host name.

License

Apache License

Return

hostname

Declaration

public static String getHostName() 

Method Source Code


//package com.java2s;
/*//www .  j  a  v a  2s.c o m
 * Copyright 2013 Proofpoint Inc.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

import java.io.*;
import java.net.*;

public class Main {
    /**
     * Returns the host name. First tries to execute "hostname" on the machine. This should work for Linux, Windows,
     * and Mac. If, for some reason hostname fails, then get the name from InetAddress (which might change depending
     * on network setup)
     *
     * @return hostname
     */
    public static String getHostName() {
        try {
            Runtime run = Runtime.getRuntime();
            Process process = run.exec("hostname");
            InputStreamReader isr = new InputStreamReader(process.getInputStream());
            BufferedReader br = new BufferedReader(isr);

            // Need to read all lines from the stream or the process could hang
            StringBuilder buffer = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null)
                buffer.append(line);

            int returnValue = process.waitFor();
            if (returnValue == 0)
                return buffer.toString();
        } catch (Exception e) {
            // ignore
        }

        try {
            return InetAddress.getLocalHost().getHostName();
        } catch (UnknownHostException e) {
            return "";
        }
    }
}

Related

  1. getHostName()
  2. getHostName()
  3. getHostname()
  4. getHostname()
  5. getHostName()
  6. getHostname()
  7. getHostName()
  8. getHostName()
  9. getHostname()