Java Host Name Get getHostname()

Here you can find the source of getHostname()

Description

get Hostname

License

Open Source License

Declaration

public static String getHostname() throws IOException, InterruptedException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class Main {
    public static String getHostname() throws IOException, InterruptedException {
        String hostname = null;//  ww w .  jav a  2 s . c  o  m
        try {
            hostname = getHostnameFromInetAddress();
        } catch (UnknownHostException unhe) {
            hostname = getHostnameFromCommand();
        }
        return hostname;
    }

    public static String getHostnameFromInetAddress() throws UnknownHostException {
        String hostname = null;
        InetAddress addr = InetAddress.getLocalHost();
        hostname = addr.getHostName();
        return hostname;
    }

    public static String getHostnameFromCommand() throws InterruptedException, IOException {
        String hostname = null;
        String command = "hostname";
        Process process = Runtime.getRuntime().exec(command);
        BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String line = null;
        StringBuilder sb = new StringBuilder();
        while ((line = input.readLine()) != null) {
            sb.append(line);
        }
        hostname = sb.toString();
        process.waitFor();
        return hostname;
    }
}

Related

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