如何在 Java 中显示和存储系统的 Public IP 地址

How to display and store Public IP address of a system in Java

我正在尝试显示和存储系统的 Public IP 地址。我使用了以下代码。 IE。, 我导入了以下两个语句:

 import java.net.InetAddress;
 import java.net.UnknownHostException;

  try {
        InetAddress iAddress = InetAddress.getLocalHost();            
        String currentIp = iAddress.getHostAddress();
        System.out.println("Current System's IP address is : " +currentIp); 
        } catch (UnknownHostException e) {
              System.out.println("Catch block executed. So IP address is not displayed");
            }

它显示输出为:

 "Current System's IP address is : 192.168.1.5"

但是我系统的 public IP 地址(在 https://www.whatismyip.com/ 中检查)是:

 115.107.244.81

那么我应该如何从 .JAVA 文件中获取并显示 public IP 地址?

https://www.whatismyip.com -> 这将显示外部世界已知的 public ip 地址。如果您重新启动系统,那么您可以看到不同的 IP 地址。即使您拥有静态 IP 地址,网站也不会显示您的机器 IP 地址。

Java 代码输出显示您的系统 ip 地址,它将用于相互通信,这是您的实际系统 ip 地址。您可以在 shell/command 提示符中验证。

ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            HttpServletRequest servletRequest = attributes.getRequest();
            ipAddress = String.valueOf(servletRequest.getSession().getAttribute("clientAddress"));

如果您使用的是来自局域网的网络,那么它总是以 192 开头。某事..

Try to connect with other mode of net connection they it will show the public ip address. Command to get ip address is ipconfig in command prompt in Windows.