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


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

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

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

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