java 如何获取本机所有ip地址呢?
下文笔者讲述java代码获取所有ip地址的方法分享,如下所示:
实现思路: 使用NetworkInterface.getNetworkInterfaces()方法 即可获取本机所有NetworkInterface
获取本机所有ip信息的方法分享
public static list<String> getLocalIPList() { List<String> ipList = new ArrayList<String>(); try { Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); NetworkInterface networkInterface; Enumeration<InetAddress> inetAddresses; InetAddress inetAddress; String ip; while (networkInterfaces.hasMoreElements()) { networkInterface = networkInterfaces.nextElement(); inetAddresses = networkInterface.getInetAddresses(); while (inetAddresses.hasMoreElements()) { inetAddress = inetAddresses.nextElement(); if (inetAddress != null && inetAddress instanceof Inet4Address) { // IPV4 ip = inetAddress.getHostAddress(); ipList.add(ip); } } } } catch (SocketException e) { e.printStackTrace(); } return ipList; }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。