All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.hecloud.runtime.common.utils.NicDetector Maven / Gradle / Ivy

package com.hecloud.runtime.common.utils;

import com.hecloud.runtime.common.enums.Platform;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 网卡工具类
 *
 * @author LoveinBJ
 */
public class NicDetector {

    private static Logger logger = LoggerFactory.getLogger(NicDetector.class);

    public static String getIp() {
        List ipList = parseIP();
        if (ipList.isEmpty()) {
            return "";
        } else {
            return ipList.get(0);
        }
    }

    public static boolean isIp(String ip) {
        if (StringUtils.isEmpty(ip) || ip.length() < 7 || ip.length() > 15) {
            return false;
        }
        /**
         * 判断IP格式和范围
         */
        String expression = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(ip);
        return matcher.find();
    }

    public static boolean isNotIp(String ip) {
        return !isIp(ip);
    }

    public static List getIPList() {
        return parseIP();
    }

    private static List parseIP() {
        List ipList = new ArrayList<>();
        try {
            if (OperatingSystem.getPlatform() == Platform.Windows) {
                ipList.add(InetAddress.getLocalHost().getHostAddress());
                return ipList;
            }
            Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface networkInterface = interfaces.nextElement();
                String network = networkInterface.getName();
                if (network.substring(0, 1).toLowerCase().equals("e")) {
                    Enumeration addresses = networkInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress address = (InetAddress) addresses.nextElement();
                        if (address instanceof Inet6Address) {
                            continue;
                        }
                        ipList.add(address.getHostAddress());
                    }
                }
            }
        } catch (SocketException e) {
            logger.error("Get Host Ip Address exception:", e);
        } catch (UnknownHostException e) {
            logger.error("Get Host Ip Address exception:", e);
        }
        return ipList;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy