获取服务器的ip地址

/**
 * @ClassName IpUtil
 * @Description TODO
 * @Author wushaopei
 * @Date 2019/7/22 10:15
 * @Version 1.0
 */
public class IpUtil {
    private static final Logger logger = LoggerFactory.getLogger( IpUtil.class );

    //获取服务器地址
    public static String getLocalIP() {
        String sIP = "";
        InetAddress ip = null;
        try {
            boolean bFindIP = false;
            Enumeration netInterfaces = (Enumeration) NetworkInterface
                    .getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                if (bFindIP) {
                    break;
                }
                NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
                Enumeration ips = ni.getInetAddresses();
                while (ips.hasMoreElements()) {
                    ip = (InetAddress) ips.nextElement();
                    if (!ip.isLoopbackAddress() && ip.getHostAddress().matches("(\\d{1,3}\\.){3}\\d{1,3}")) {
                        bFindIP = true;
                        break;
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        if (null != ip) {
            sIP = ip.getHostAddress();
        }
        return sIP;
    }
    
    //根据配置获取当前服务器地址,用于校验ip地址是否正确
    public static int compareIp(){
        //获取服务器的ip地址
        String serverIp = IpUtil.getLocalIP();
        logger.info("获取服务器的ip地址serverIp:{}",serverIp);
        //获取appolo配置的ip地址
        Config config = ConfigService.getConfig("YFB.alpha-game.basic");
        String appoloIp = config.getProperty("compareUrl", null);
        logger.info("获取appolo配置的ip地址appoloIp:{}",appoloIp);

        if(!serverIp.equals(appoloIp)){
            return 0;
        }
        return 1;
    }
}

测试:

String s = IpUtil.getLocalIP();
 int i = IpUtil.compareIp();

 

你可能感兴趣的:(工具类)