Java之获取本机所有IP

IP工具类:

//获取本机所有IP地址
public class IpUtil {
	public static List getLocalIPList() {
        List ipList = new ArrayList();
        try {
            Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces();
            NetworkInterface networkInterface;
            Enumeration 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;
    }
}

测试类:

List ip = IpUtil.getLocalIPList();
System.out.println("本机Ip为:"+ip);

输出结果为:
在这里插入图片描述
之后经过测试发现,如果仅获取IPv4,可以直接用JDK获取:

System.out.println("本机IPv4为:"+InetAddress.getLocalHost().getHostAddress());

输出结果为:
在这里插入图片描述

你可能感兴趣的:(Java)