Java获取本机ip地址

来源:互联网 发布:钣金展开软件下载 编辑:程序博客网 时间:2024/05/24 07:23

InnetAddress这个Java类,可以获取到,机器占有的ip地址。

然而,这类在windows下可以正常工作,但是在Linux下就呵呵了,返回的永远是127.0.0.1,这对于我们开发是没有帮助的。

   InetAddress inetAddress = InetAddress.getLocalHost();        String str = inetAddress.getHostAddress();        System.out.println(str);

但是还有其他的方式来获取,就是使用NetworkInterface类,但是这个类获取的是所有网络接口的地址

Enumeration<NetworkInterface> netInterfaces = null;        try {            netInterfaces = NetworkInterface.getNetworkInterfaces();            while (netInterfaces.hasMoreElements()) {                NetworkInterface ni = netInterfaces.nextElement();                System.out.println("DisplayName:" + ni.getDisplayName());                System.out.println("Name:" + ni.getName());                Enumeration<InetAddress> ips = ni.getInetAddresses();                while (ips.hasMoreElements()) {                    System.out.println("IP:"                            + ips.nextElement().getHostAddress());                }                System.out.println("-------------------------");            }        } catch (Exception e) {            e.printStackTrace();        }

会把虚拟网卡,虚拟机占用的ip,还有一些特殊的保留地址如169开头的地址。

所以需要根据自己的实际需求,来获取正确的ip地址。

所以从里可以看出Java跨平台也不是完美的。

当然如果在web环境下,最直接的就是Request.getLocalAddr()方法来获取ip地址。