3

可能重复:
如何在 java 中
获取用户 IP 地址使用 URL 字符串获取 IP 地址?(爪哇)

链接是:

"http://automation.whatismyip.com/n09230945.asp"

上面的链接返回外部 IP。

我尝试制作自己的代码来获取我的 IP,如上面的链接

我的代码是

String my_own_ip =InetAddress.getLocalHost().getHostAddress();

那么如何获得这个IP

在此代码中返回我的内部 IP

我在局域网连接我的局域网 IP 是 192.168.0.109

外部 IP 为 27.54.180.156

I want 27.54.180.156

提前致谢

4

3 回答 3

3

不要使用getLocalHost()- 这将返回您的本地主机

InetAddrsss addy = InetAddress.getByName("www.stackoverflow.com");
System.out.println(addy.getHostAddress());

请注意,您需要省略协议http://

InetAddrsss addy = InetAddress.getByName("http://www.stackoverflow.com"); // throws an exception
System.out.println(addy.getHostAddress());

...同样的路径:

InetAddrsss addy = InetAddress.getByName("www.stackoverflow.com/questions"); // throws an exception
System.out.println(addy.getHostAddress());
于 2012-12-12T04:08:54.103 回答
1

问题是您假设您的计算机可以访问外部 IP 地址,而实际上它没有。只有路由器和外部连接才能访问 IP 地址。

话虽这么说,您最好的选择是使用http://icanhazip.comhttp://checkip.dyndns.org之类的网站(或者您提供的网站http://automation.whatismyip.com /n09230945.asp)并使用 Java 客户端上的 HTTP Get 连接到它,就像在这个问题这个问题中一样。取回 HTML 页面后,对其进行解析以找到 IP 地址。这可以使用正则表达式来完成,因为这些是非常简单的 HTML 页面,不需要大量的 DOM 解析:

String html = ... ;
Pattern pattern = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3}");
Matcher matcher = pattern.matcher(html);
matcher.find();
String ip = matcher.group(0);

诀窍是找到一个具有免费 API 的网站,您可以根据需要多次调用该网站。据我所知,我上面列出的两个没有任何限制。

于 2012-12-12T04:52:41.867 回答
-1

您可以简单地使用 jsp 页面中的代码并将其打印到文档的正文中。

<%@page import="java.net.InetAddress" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 <% String my_own_ip =InetAddress.getLocalHost().getHostAddress();%>
    <%=my_own_ip%>
</body>
</html>
于 2012-12-12T04:20:46.373 回答