java InetAddress.getLocalHost(); 返回127.0.0.1…如何获得

我正在编写一个简单的网络应用程序...我需要知道我的机器在网络上的真实IP,例如192.168.1.3。getLocalHost返回127.0.0.1(在Linux上,如果在Windows上相同,则为dunno)怎么做?



GCT1015
浏览 2321回答 3
3回答

白衣染霜花

由于机器可能有多个地址,因此很难确定哪个地址适合您。通常,您希望系统根据其路由表分配IP。由于结果取决于您要连接的IP,因此有一个简单的技巧:只需创建一个连接,然后查看您从操作系统获得的地址即可:// output on my machine: "192.168.1.102"Socket s = new Socket("192.168.1.1", 80);System.out.println(s.getLocalAddress().getHostAddress());s.close();// output on my machine: "127.0.1.1"System.out.println(InetAddress.getLocalHost().getHostAddress());我不确定是否可以在不建立连接的情况下执行此操作。我认为我曾经设法用Perl(或C?)做到这一点,但是不要问我有关Java的问题。我认为可能无需实际连接即可创建UDP套接字(DatagramSocket)。如果途中有NAT路由器,您将无法获得远程主机可以看到的IP。但是,以您给出的192. *为例,我认为您不在乎。

隔江千里

这是避免IPv6和环回结果的方法。public InetAddress getCurrentIp() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Enumeration<NetworkInterface> networkInterfaces = NetworkInterface&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .getNetworkInterfaces();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while (networkInterfaces.hasMoreElements()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; NetworkInterface ni = (NetworkInterface) networkInterfaces&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .nextElement();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Enumeration<InetAddress> nias = ni.getInetAddresses();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while(nias.hasMoreElements()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; InetAddress ia= (InetAddress) nias.nextElement();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (!ia.isLinkLocalAddress()&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&& !ia.isLoopbackAddress()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&& ia instanceof Inet4Address) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return ia;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } catch (SocketException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; LOG.error("unable to get current IP " + e.getMessage(), e);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java