package com.mini.capi.config.component;

import org.springframework.stereotype.Component;

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

@Component
public class AppNetworkInfo {

    // 获取主机名
    public String getHostName() throws UnknownHostException {
        return InetAddress.getLocalHost().getHostName();
    }

    // 获取本地 IP 地址（可能是内网 IP）
    public String getLocalIp() throws UnknownHostException {
        return InetAddress.getLocalHost().getHostAddress();
    }

    // 获取所有有效 IPv4 地址（过滤回环地址、IPv6，支持多网卡）
    public List<String> getAllIps() throws SocketException {
        List<String> ips = new ArrayList<>();
        Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            NetworkInterface ni = interfaces.nextElement();
            // 跳过虚拟网卡、禁用的网卡
            if (ni.isLoopback() || !ni.isUp()) {
                continue;
            }
            Enumeration<InetAddress> addresses = ni.getInetAddresses();
            while (addresses.hasMoreElements()) {
                InetAddress addr = addresses.nextElement();
                // 只保留 IPv4 地址
                if (addr instanceof Inet4Address) {
                    ips.add(addr.getHostAddress());
                }
            }
        }
        return ips;
    }
}
