# 获取 IP 地址的 Java 程序

> 原文： [https://beginnersbook.com/2014/07/java-program-to-get-ip-address/](https://beginnersbook.com/2014/07/java-program-to-get-ip-address/)

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

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

```java
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());
  }
}
```

**输出：**

```java
My IP Address is:
115.242.7.243
```

**参考：**
[InetAddress javadoc](https://docs.oracle.com/javase/7/docs/api/java/net/InetAddress.html)