Skip to content

Latest commit

 

History

History
45 lines (34 loc) · 1.31 KB

File metadata and controls

45 lines (34 loc) · 1.31 KB

Java 程序:获取 IP 地址

原文: https://beginnersbook.com/2014/07/java-program-to-get-ip-address/

在这个例子中,我们将看到如何获得系统的 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