Java 实例 获取 IP 地址

在这个例子中,我们将看到如何获得系统的 IP 地址。步骤如下:

1)通过调用InetAddress类的getLocalHost()方法获取本地主机地址。

2)通过调用getHostAddress()方法获取 IP 地址。

import java.net.InetAddress;

class GetMyIPAddress
{
   public static void main(String args[]) throws Exception
   {
      /* public static InetAddress getLocalHost()
       * throws UnknownHostException: Returns the address 
       * of the local host. This is achieved by retrieving 
       * the name of the host from the system, then resolving 
       * that name into an InetAddress. Note: The resolved 
       * address may be cached for a short period of time.
       */
      InetAddress myIP=InetAddress.getLocalHost();

      /* public String getHostAddress(): Returns the IP 
       * address string in textual presentation.
       */
      System.out.println("My IP Address is:");
      System.out.println(myIP.getHostAddress());
  }
}

输出:

My IP Address is:
115.242.7.243

参考:

InetAddress javadoc

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

Java 示例