get Computer Name from Host - Java Network

Java examples for Network:Host

Description

get Computer Name from Host

Demo Code


import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;

public class Main{
    public static void main(String[] argv) throws Exception{
        System.out.println(getComputerName());
    }/*from  w w w . ja  va  2  s  . c  o  m*/
    
    public static final String IPADDRESS = "0.0.0.0";
    public static String getComputerName() {

        String hostname = null;

        try {
            hostname = InetAddress.getLocalHost().getHostName();
        } catch (java.net.UnknownHostException uhe) {

        }
        return hostname;
    }
    
    public static String getHostName() {

        String hostname = null;

        try {
            hostname = InetAddress.getLocalHost().getHostName();
        } catch (java.net.UnknownHostException uhe) {

        }
        //hostname = "testmachine";
        return hostname + "[@" + AddressUtil.getIPAddress() + "]";
    }
    
    public static String getIPAddress() {
        String ip = IPADDRESS;

        try {
            String ha = InetAddress.getLocalHost().getHostAddress();
            InetAddress[] a = InetAddress.getAllByName(ha);

            if (a.length == 1) {
                ip = a[0].getHostAddress();
            }
        } catch (UnknownHostException uhe) {
        }

        return ip;
    }
}

Related Tutorials