package com.ssyf.test;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;

public class Test2 {

    public static void main(String[] args) {

        System.out.println(getAvailableLocalIps());
    }

    /**
     * 获取本机所有可用的 IPv4 地址（排除 127.0.0.1）
     */
    public static List<String> getAvailableLocalIps() {
        List<String> ipList = new ArrayList<>();
        try {
            // 获取所有网络接口（网卡）
            Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();

            for (NetworkInterface netint : Collections.list(nets)) {
                // 排除未开启、回环(loopback)、虚拟接口(可选)
                if (!netint.isUp() || netint.isLoopback() || netint.isVirtual()) {
                    continue;
                }

                // 获取该网卡下的所有 IP 地址
                Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
                for (InetAddress inetAddress : Collections.list(inetAddresses)) {
                    // 只取 IPv4，并且排除回环地址
                    if (inetAddress instanceof Inet4Address && !inetAddress.isLoopbackAddress()) {
                        String ip = inetAddress.getHostAddress();
                        System.out.println("发现可用本地IP: " + ip);
                        ipList.add(ip);
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
        }
        return ipList;
    }
}
