Get the IP Address of the Current Machine Using Java – 用Java获取当前机器的IP地址

最后修改: 2022年 4月 26日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

IP address or Internet Protocol address uniquely identifies a device on the Internet. Therefore, knowing the identity of the device running our application is a key part of some applications.

IP地址或互联网协议地址能够唯一地识别互联网上的设备。因此,了解运行我们应用程序的设备的身份是某些应用程序的一个关键部分。

In this tutorial, we’ll check out various methods to retrieve the IP address of our computer using Java.

在本教程中,我们将查看使用Java检索计算机IP地址的各种方法。

2. Find the Local IP Address

2.找到本地的IP地址

First, let’s look at some methods for obtaining the local IPv4 address of the current machine.

首先,让我们看一下获取当前机器的本地IPv4地址的一些方法。

2.1. Local Address with Java Net Library

2.1.使用Java Net库的本地地址

This method uses the Java Net library to make a UDP connection:

这个方法使用Java Net库来进行UDP连接。

try (final DatagramSocket datagramSocket = new DatagramSocket()) {
    datagramSocket.connect(InetAddress.getByName("8.8.8.8"), 12345);
    return datagramSocket.getLocalAddress().getHostAddress();
}

Here, for simplicity, we are using Google’s primary DNS as our destination host and supplying the IP address 8.8.8.8. The Java Net Library checks only the validity of the address format at this point, so the address itself can be unreachable. Moreover, we are using a random port 12345 to create a UDP connection with the socket.connect() method. Under the hood, it sets all the variables needed for sending and receiving data, including the machine’s local address, without actually sending any request to the destination host.

在这里,为了简单起见,我们使用Google的主要DNS作为我们的目标主机,并提供IP地址8.8.8.8.,Java Net Library在这一点上只检查地址格式的有效性,所以地址本身可能是不可达的。此外,我们使用一个随机端口12345,用socket.connect()方法创建一个UDP连接。在引擎盖下,它设置了发送和接收数据所需的所有变量,包括机器的本地地址,而实际上没有向目标主机发送任何请求。

While this solution works very well on Linux and Windows machines, it is problematic on macOS and doesn’t return the expected IP address.

虽然这个解决方案在Linux和Windows机器上效果很好,但在macOS上却有问题,不能返回预期的IP地址。

2.2. Local Address With Socket Connection

2.2.有插座连接的本地地址

Alternatively, we can use a socket connection through a reliable internet connection to look up the IP address:

另外,我们可以使用通过可靠的互联网连接的套接字连接来查询IP地址

try (Socket socket = new Socket()) {
    socket.connect(new InetSocketAddress("google.com", 80));
    return socket.getLocalAddress().getHostAddress();
}

Here, again for simplicity, we used google.com with a connection on port 80 to get the host address. We might use any other URL for creating a socket connection as long as it is reachable.

在这里,为了简单起见,我们使用google.com80端口的连接来获取主机地址。我们可以使用任何其他的URL来创建一个套接字连接,只要它是可到达的。

2.3. Caveats on Complex Network Situations

2.3.关于复杂网络情况的注意事项

The methods listed above work very well in the case of simple network situations. However, in cases where the machine has more network interfaces, the behavior might not be as predictable.

上面列出的方法在简单的网络情况下效果很好。然而,在机器有更多网络接口的情况下,行为可能就不那么容易预测了。

In other words, the IP address returned from the functions described above will be the address of the preferred network interface on the machine. Consequently, it can be different from the one we are expecting. For specific needs, we can find the IP Address of a Client Connected to a Server.

换句话说,从上述函数返回的IP地址将是机器上首选网络接口的地址。因此,它可能与我们所期望的不同。对于特定的需求,我们可以查找连接到服务器的客户端的IP地址

3. Find the Public IP Address

3.找到公共IP地址

Similar to the local IP address, we might want to know the public IP address of the current machine. A public IP address is an IPv4 address reachable from the internet. Moreover, it might not uniquely identify the machine looking up the address. For example, multiple hosts under the same router have the same public IP address.

与本地IP地址类似,我们可能想知道当前机器的公共IP地址。公共IP地址是一个可从互联网上到达的IPv4地址。此外,它可能无法唯一地识别查询该地址的机器。例如,同一台路由器下的多台主机拥有相同的公共IP地址。

Simply, we can connect to the Amazon AWS checkip.amazonaws.com URL and read the response:

简单地说,我们可以连接到亚马逊AWS的checkip.amazonaws.com URL并读取响应。

String urlString = "http://checkip.amazonaws.com/";
URL url = new URL(urlString);
try (BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) {
    return br.readLine();
}

This works well most of the time. However, we explicitly depend on an external source whose reliability cannot be guaranteed. Therefore, as a fallback, we can use any of these URLs to retrieve the public IP address:

这在大多数情况下效果很好。然而,我们明确依赖于一个外部来源,其可靠性无法保证。因此,作为后备方案,我们可以使用这些URL中的任何一个来检索公共IP地址

  • https://ipv4.icanhazip.com/
  • http://myexternalip.com/raw
  • http://ipecho.net/plain

4. Conclusion

4.总结

In this article, we learned how to find IP addresses of the current machine and how to retrieve them using Java. We also looked at various methods for checking both local and public IP addresses.

在这篇文章中,我们学习了如何查找当前机器的IP地址,以及如何用Java检索这些地址。我们还研究了检查本地和公共IP地址的各种方法。

And as always, the source code for the examples is available over on GitHub.

像往常一样,这些例子的源代码可以在GitHub上找到