简体   繁体   English

如何使用Java显示和存储系统的公共IP地址

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

I am trying to display and store the Public IP address of a system. 我正在尝试显示和存储系统的公共IP地址。 I used the following code for the same. 我使用以下代码相同。 ie, I have imported following two statements : 即,我已导入以下两个语句:

 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");
            }

It is displaying the output as : 它显示为:

 "Current System's IP address is : 192.168.1.5"

But my system's public IP address (as checked in https://www.whatismyip.com/ ) is : 但是我系统的公共IP地址(在https://www.whatismyip.com/中检查)是:

 115.107.244.81

So how should I fetch and display the public IP address from .JAVA file? 那么,如何从.JAVA文件中获取并显示公共IP地址?

https://www.whatismyip.com -> which will display the public ip address which will be known to the outside world. https://www.whatismyip.com- >将显示外界已知的公共IP地址。 If you restart your system then you can see different ip address. 如果重新启动系统,则可以看到其他IP地址。 Eventhough if you are having a static ip address the website won't show your machine ip address. 即使您有一个静态IP地址,该网站也不会显示您的机器IP地址。

Java code output shows your system ip address which will be used for inter communication and that is your actual system ip address. Java代码输出显示您的系统IP地址,该IP地址将用于内部通信,这是您的实际系统IP地址。 you can verify that in shell/command prompt. 您可以在shell /命令提示符中进行验证。

if your are using net from local area network then it always start with 192. something .. 如果您使用的是局域网中的网络,则始终以192开始。

Try to connect with other mode of net connection they it will show the public ip address. 尝试使用其他方式的网络连接进行连接,它们会显示公共IP地址。 Command to get ip address is ipconfig in command prompt in Windows. 在Windows的命令提示符中,获取IP地址的命令是ipconfig。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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