get Host Name - Java Network

Java examples for Network:URL

Description

get 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(getHostName());
    }/*  www  .j av  a2 s  .c o  m*/

    public static String getHostName() {
        String server = null;

        // Obtain server name of local host
        try {
            final InetAddress localMachine = InetAddress.getLocalHost();
            server = localMachine.getHostName();
        } catch (final UnknownHostException e) {
            server = "Unknown";
        }
        return server;
    }

    public static String getHostName(String ipAddress) {
        String server = null;
        try {
            // Get hostname by textual representation of IP address
            final InetAddress addr = InetAddress.getByName(ipAddress);
            server = addr.getHostName();
        } catch (final UnknownHostException e) {
            server = ipAddress;
        }
        return server;

    }
}

Related Tutorials