用Java获取“外部”IP地址

时间:2010-05-30 15:27:18

标签: java networking network-programming ip-address external

我不太确定如何获取机器的外部IP地址,因为网络外的计算机会看到它。

我的以下IPAddress类只获取本机的本地IP地址。

public class IPAddress {

    private InetAddress thisIp;

    private String thisIpAddress;

    private void setIpAdd() {
        try {
            InetAddress thisIp = InetAddress.getLocalHost();
            thisIpAddress = thisIp.getHostAddress().toString();
        } catch (Exception e) {
        }
    }

    protected String getIpAddress() {
        setIpAdd();
        return thisIpAddress;
    }
}

12 个答案:

答案 0 :(得分:155)

我不确定您是否可以从本地计算机上运行的代码中获取该IP。

然而,您可以构建在网站上运行的代码,例如在JSP中运行,然后使用返回请求来源的IP的内容:

request.getRemoteAddr()

或者只是使用已经存在的服务,然后解析服务中的答案以找出IP。

使用AWS等网络服务

import java.net.*;
import java.io.*;

URL whatismyip = new URL("http://checkip.amazonaws.com");
BufferedReader in = new BufferedReader(new InputStreamReader(
                whatismyip.openStream()));

String ip = in.readLine(); //you get the IP as a String
System.out.println(ip);

答案 1 :(得分:75)

@stivlo的评论之一值得回答:

您可以使用亚马逊服务http://checkip.amazonaws.com

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;

public class IpChecker {

    public static String getIp() throws Exception {
        URL whatismyip = new URL("http://checkip.amazonaws.com");
        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(
                    whatismyip.openStream()));
            String ip = in.readLine();
            return ip;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

答案 2 :(得分:16)

事实是,'你不能',因为你提出了这个问题。 NAT发生在协议之外。您的计算机内核无法知道您的NAT盒如何从外部IP地址映射到内部IP地址。这里的其他答案提供了涉及与外部网站交谈的方法。

答案 3 :(得分:11)

正如@Donal Fellows所写,你必须查询网络接口而不是机器。来自javadocs的代码对我有用:

以下示例程序列出了计算机上的所有网络接口及其地址:

import java.io.*;
import java.net.*;
import java.util.*;
import static java.lang.System.out;

public class ListNets {

    public static void main(String args[]) throws SocketException {
        Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
        for (NetworkInterface netint : Collections.list(nets))
            displayInterfaceInformation(netint);
    }

    static void displayInterfaceInformation(NetworkInterface netint) throws SocketException {
        out.printf("Display name: %s\n", netint.getDisplayName());
        out.printf("Name: %s\n", netint.getName());
        Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
        for (InetAddress inetAddress : Collections.list(inetAddresses)) {
            out.printf("InetAddress: %s\n", inetAddress);
        }
        out.printf("\n");
     }
} 

以下是示例程序的示例输出:

Display name: TCP Loopback interface
Name: lo
InetAddress: /127.0.0.1

Display name: Wireless Network Connection
Name: eth0
InetAddress: /192.0.2.0

来自docs.oracle.com

答案 4 :(得分:10)

所有这些仍然正常并且运作顺利! (截至2016年12月19日)

建议:不要只依赖其中一个;尝试使用一个,但考虑到其他人有一个contigency计划!你使用的越多越好!

祝你好运!

答案 5 :(得分:5)

对某些网站(例如www.whatismyip.com)进行HttpURLConnection并解析: - )

答案 6 :(得分:4)

http://jstun.javawi.de/将会这样做 - 只要您的网关设备执行STUN)大多数都会这样做

答案 7 :(得分:4)

这个怎么样?它很简单,对我来说效果最好:)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;


public class IP {
    public static void main(String args[]) {
        new IP();
    }

    public IP() {
        URL ipAdress;

        try {
            ipAdress = new URL("http://myexternalip.com/raw");

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

            String ip = in.readLine();
            System.out.println(ip);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

答案 8 :(得分:1)

这并不容易,因为局域网内的机器通常不关心其路由器的外部IP到互联网......它根本不需要它!

我建议您通过打开像http://www.whatismyip.com/这样的网站来解决这个问题,并通过解析html结果来获取IP号码。这应该不会那么难!

答案 9 :(得分:0)

如果你使用的是基于JAVA的webapp,如果你想抓住客户端(通过浏览器发出请求的那个),外部ip尝试在公共域中部署应用程序并使用request.getRemoteAddr ()读取外部IP地址。

答案 10 :(得分:0)

System.out.println(pageCrawling.getHtmlFromURL("http://ipecho.net/plain"));

答案 11 :(得分:0)

另一种解决方案是执行外部命令,显然,该解决方案限制了应用程序的可移植性。

例如,对于在Windows上运行的应用程序,可以通过jPowershell执行PowerShell命令,如以下代码所示:

public String getMyPublicIp() {
    // PowerShell command
    String command = "(Invoke-WebRequest ifconfig.me/ip).Content.Trim()";
    String powerShellOut = PowerShell.executeSingleCommand(command).getCommandOutput();

    // Connection failed
    if (powerShellOut.contains("InvalidOperation")) {
        powerShellOut = null;
    }
    return powerShellOut;
}
相关问题