简体   繁体   中英

Does InetAddress.getLocalHost give ip address of Windows and Linux System?

我在我的程序中使用InetAddress.getLocalHost() ,它可以部署在 Windows 和 Linux 服务器上。它在两种环境中都提供 IP 地址吗?

The method gives an IP address on all platforms. However, it may not give you the IP address that you expect.

The javadoc says this:

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.

If there is a security manager, its checkConnect method is called with the local host name and -1 as its arguments to see if the operation is allowed. If the operation is not allowed, an InetAddress representing the loopback address is returned.

There are a variety of scenarios where IP that an application is given is not the IP address that you want or need:

  • If the application is sandboxed, the IP will be 127.0.0.1 .
  • If local DNS is configured to return 127.0.0.1 for the host's name, then that is what you will get. (I've seen systems misconfigured like that.)
  • If the system has multiple NICs, the DNS lookup might give you the IP of a non-exposed NIC.
  • If the system is actually a virtual machine, then the IP that the system sees may be different to the one that is exposed to the outside.
  • If the system's IP is in a private IP range, then it won't be addressable "publicly".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM