我們使用 InetAddress 類的 getLocalAddress() 方法獲取本機ip地址及主機名
完整代碼
import java.net.InetAddress;
public class Main {
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.3
Local host name: hang