使用Java获取外部IP地址 [英] Getting external IP address with Java

查看:292
本文介绍了使用Java获取外部IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不联系以下任何网站的情况下,仅使用Java获取计算机的外部IP:

How can I get the external IP of my computer, solely using Java, without contacting any websites like below:

String ip = "";

    try
    {

        URL whatismyip;

        whatismyip = new URL("http://checkip.amazonaws.com");

        BufferedReader in = null;

        in = new BufferedReader(new InputStreamReader(whatismyip.openStream()));

        ip = in.readLine();

    } catch (UnknownHostException e)
    {
        e.printStackTrace();
    } catch (MalformedURLException e)
    {
        e.printStackTrace();
    } catch (IOException e)
    {
        e.printStackTrace();
    }

我不想要这个的原因是这个网站是否因为那天,我会遇到很大的问题。

The reason I do not want this is if this site is down for even a day, I will have big problems.

编辑:

要更清楚地定义问题:Java有什么方法可以获得用户的机器IP,如果有的话,它们是什么?

To define the question a bit clearer: Does Java have any methods to get the user's machine IP, if so, what are they?

推荐答案

假设你在一个典型的家庭环境中(计算机 - 路由器 - 互联网)使用NAT,您无法从本地计算机上运行的程序获取该地址(如83.154.48.7)。您可以做的最多就是获取安装在其上的网络适配器的地址(地址如192.0.0.1),因为外部地址实际上是路由器的地址。

Assuming you are in a typical home enviroment (computer - router - internet) using NAT you cannot get that address (something like 83.154.48.7) from a program running in a local machine. The most you can do is get the address of the network adapters installed on it (addresses like 192.0.0.1), since the 'external' address is actually the address of the router.

您需要询问外部网站,因为他们将回答路由器的地址(83.154.48.7),路由器会将答案发送到您的电脑。

You need to ask a external site because they will answer to the address of the router (the 83.154.48.7) and the router will send the answer to your pc.

可能性是询问路由器的IP,但从PC上看,路由器的网络地址为192.0.0.255。 (不知道你是否可以在路由器中获取所有地址并过滤它们)

A posibility could be to ask the router for his IP, but viewed from the PC, the router will have an address like 192.0.0.255 for that network. (Dont know if you can get ALL addresses in the router and filter them, though)


如果有一天这个网站关闭,我会有大问题。

For if one day this site down, I will have big problems.

你可以有一个网站列表,你可以从中获取地址,并逐个尝试,直到其中一个他们起来了。

You can have a list of sites where you can get the address from, and try one by one until one of them is up.

这篇关于使用Java获取外部IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆