[공부용]참고 사이트 모음/[java]

[Java] 현재 컴퓨터 이름 얻기 InetAddress.getLocalHost().getHostName();

bled 2020. 12. 4. 14:19
import java.net.InetAddress;

public class ComputerName {

    /**
     * @param args
     */
    public static void main(String[] args) {

        String computerName = null;
        try {
            computerName = InetAddress.getLocalHost().getHostName();
            System.out.println(computerName);
        } catch (Exception ex) {
        }

    }

m.blog.naver.com/PostView.nhn?blogId=redfreek2c&logNo=120122855507&proxyReferer=https:%2F%2Fwww.google.com%2F


InetAddress.getLocalHost().getHostName() 사용 시 UnknownHostException 

// 아래처럼 사용할 경우 DNS구성이 되어있지 않으면 UnknownHostException이 발생한다.
try {
    hostname = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
    e.printStackTrace();
}
 
// 웹 검색에서 찾은 방법 하나
try {
    hostname = InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
    hostname = e.getMessage(); // host = "hostname: hostname"
    if ( hostname != null ) {
        int colon = hostname.indexOf(':');
        if ( colon>0 ) {
            return hostname.substring(0, colon); // Dangerous, this is JVM dependant code.
        }
    }
    e.printStackTrace();
}

luvispain.tistory.com/7