Java 范例 - 获取本机 ip 地址及主机名
使用 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); } }
编译运行以上 Java 代码,输出结果如下
Local HostAddress: 192.168.1.4 Local host name: harsh