如何使用Java获取客户端的LAN IP?
如何使用 Java 获取计算机的 LAN IP 地址?我想要连接到路由器和网络其余部分的 IP 地址。
我尝试过这样的事情:
Socket s = new Socket("www.google.com", 80);
String ip = s.getLocalAddress().getHostAddress();
s.close();
这似乎在某些情况下有效,但有时它会返回环回地址或完全不同的东西。此外,它需要互联网连接。
有谁有更准确的方法来做到这一点?
编辑:认为在这里提问比在评论中提问更好。
如果你有很多接口怎么办?例如,一种用于电缆,一种用于 WiFi,一种用于虚拟盒等。是否无法实际看到哪一个连接到网络?
How can i get the LAN IP-address of a computer using Java? I want the IP-address which is connected to the router and the rest of the network.
I've tried something like this:
Socket s = new Socket("www.google.com", 80);
String ip = s.getLocalAddress().getHostAddress();
s.close();
This seem to work on some cases, but sometimes it returns the loopback-address or something completely different. Also, it requires internet connection.
Does anyone got a more accurate method of doing this?
EDIT: Thought it would be better to ask here than in a comment..
What if you got many interfaces? For example, one for cable, one for wifi and one for virtual box or so. Is it impossible to actually see which one is connected to the network?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
尝试 java.net.NetworkInterface
Try java.net.NetworkInterface
首先:没有单一的地址。您的机器至少有两个地址(“lo”上的 127.0.0.1,“eth1”上的可能是 192.168.1.1)。
您想要这个: 列出网络接口
如您所料,您无法自动检测哪一个连接到您的任何路由器,因为这可能需要对您的路由表进行复杂的解析。但如果您只想要任何非本地地址,这应该足够了。可以肯定的是,请尝试在 Vista 或 Windows 7 上至少使用一次此功能,因为它们添加了 IPv6 地址。
以下是示例程序的示例输出:
At first: There is no single address. Your machine has at least two adresses (127.0.0.1 on "lo" and maybe 192.168.1.1 on "eth1").
You want this: Listing network interfaces
As you may expect, you cannot automatically detect which one is connected to any of your routers, since this needs potentially complex parsing of your routing tables. But if you just want any non-local address this should be enought. To be sure, try to use this at least one time on vista or Windows 7, since they add IPv6 addresses.
The following is sample output from the example program:
这是我已经使用了一段时间的方法。它还包括一些小技巧来找出外部可见的 IP 地址。
This is a method I've used for a while. It includes a little hack to figure out the externally visible ip-address as well.
正如丹尼尔已经指出的那样,您无法知道哪个接口是“连接”的。例如,如果计算机有多个网络接口卡,并且都连接到单独的物理 LAN,该怎么办?
让用户决定使用哪个界面或尝试所有界面,具体取决于您的用例。
As Daniel already pointed out, you cannot know which interface is the one "connected". What if, for example, the computer has multiple network interface cards which are both connected to separate physical LANs?
Let the user decide which interface to use or try them all, depending on what your use case is.