get Local Host Name - Java Network

Java examples for Network:Host

Description

get Local Host Name

Demo Code


//package com.java2s;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class Main {
    public static void main(String[] argv) throws Exception {
        System.out.println(getLocalHostName());
    }/*from   w w  w . j  ava 2  s .c  om*/

    public static String getLocalHostName() throws UnknownHostException {
        try {
            return (InetAddress.getLocalHost()).getHostName();
        } catch (UnknownHostException uhe) {
            String host = uhe.getMessage(); // host = "hostname: hostname"
            if (host != null) {
                int colon = host.indexOf(':');
                if (colon > 0) {
                    return host.substring(0, colon);
                }
            }
            throw uhe;
        }
    }
}

Related Tutorials