我想用Java获取我的Internet IP地址,但是当我的IP地址是192.168.0.xxx时,我一直得到我的本地地址(即:127.0.0.1)
我正在使用这条线:
InetAddress.getLocalHost().getHostAddress();
Run Code Online (Sandbox Code Playgroud)
这似乎是获取IP地址的标准,但它不是我想要的.每个教程都说使用这一行,所以我有点困惑.
谁能告诉我如何获得正确的IP地址?
我正在运行连接到WiFi的设备,而我没有使用任何电缆.我使用ifconfig inet addr给出的IP连接到服务器,我希望得到设备的inet addr.我可以检查服务器端套接字的IP,但是如果设备(客户端)告诉服务器他希望其他设备连接哪个IP,那就更好了.
roy*_*rie 40
String ip;
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface iface = interfaces.nextElement();
// filters out 127.0.0.1 and inactive interfaces
if (iface.isLoopback() || !iface.isUp())
continue;
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while(addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
ip = addr.getHostAddress();
System.out.println(iface.getDisplayName() + " " + ip);
}
}
} catch (SocketException e) {
throw new RuntimeException(e);
}
Run Code Online (Sandbox Code Playgroud)
biz*_*lop 19
该NetworkInterface类别包括所有相关的方法,但要注意,有作为"我的IP"没有这样的事.一台机器可以有多个接口,每个接口可以有多个IP.
您可以使用此类列出所有这些,但您从列表中选择的接口和IP取决于您使用此IP所需的内容.
(InetAddress.getLocalHost()不咨询您的接口,它只返回常量127.0.0.1(对于IPv4))
URL url = new URL("http://checkip.amazonaws.com/");
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()));
System.out.println(br.readLine());
Run Code Online (Sandbox Code Playgroud)
编辑
在你投票之前,我很清楚这不是一个java解决方案.它是任何编程语言的通用解决方案.其他解决方案对我来说效果不佳.另外我相信知道你的IP更简单的方法就是上网.它可以是任何站点,服务器可以返回它在请求中获得的客户端ip.您可以为它设置自己的端点.
| 归档时间: |
|
| 查看次数: |
73051 次 |
| 最近记录: |