Java 实例 - 获取本机ip地址及主机名

以下实例演示了如何使用 InetAddress 类的 getLocalAddress() 方法获取本机ip地址及主机名:

Main.java 文件

  1. import java.net.InetAddress;
  2. public class Main {
  3. public static void main(String[] args)
  4. throws Exception {
  5. InetAddress addr = InetAddress.getLocalHost();
  6. System.out.println("Local HostAddress:
  7. "+addr.getHostAddress());
  8. String hostname = addr.getHostName();
  9. System.out.println("Local host name: "+hostname);
  10. }
  11. }

以上代码运行输出结果为:

  1. Local HostAddress: 192.168.1.4
  2. Local host name: harsh