Gets the host name of this system. - Java Network

Java examples for Network:Host

Description

Gets the host name of this system.

Demo Code

/**//ww w . ja  v a2 s  . c o m
 * The contents of this file are subject to the AED Public Use License Agreement, Version 1.0 (the "License");
 * use in any manner is strictly prohibited except in compliance with the terms of the License.
 * The License is available at http://gatherdata.org/license.
 *
 * Copyright (c) AED.  All Rights Reserved
 */
//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(getHostName());
    }

    /**
     * Gets the hostname of this system.
     * 
     * @return hostname, or "localhost" if hostname could not be determined
     */
    public static String getHostName() {
        String hostname = null;
        try {
            InetAddress addr = InetAddress.getLocalHost();
            hostname = addr.getHostName();
        } catch (UnknownHostException e) {
            hostname = "localhost";
        }
        return hostname;
    }
}

Related Tutorials