在Java程式設計中,如何獲取本地計算機的IP地址和主機名?
以下範例顯示如何使用InetAddress
類的getLocalAddress()
方法獲取系統的本地IP地址和主機名。
package com.yiibai;
import java.net.InetAddress;
public class GetLocalIPAddress {
public static void main(String[] args) throws Exception {
InetAddress addr = InetAddress.getLocalHost();
System.out.println("Local HostAddress: " + addr.getHostAddress());
String hostname = addr.getHostName();
System.out.println("Local host name: " + hostname);
}
}
上述程式碼範例將產生以下結果 -
Local HostAddress: 192.168.1.50
Local host name: YB-PC