com.sinszm.common.util.BindNetAddressUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of szm-boot-common Show documentation
Show all versions of szm-boot-common Show documentation
基于SpringBoot扩展生态应用公共组件
Copyright © 2020 智慧程序猿 All rights reserved.
https://www.sinsz.com
package com.sinszm.common.util;
import org.springframework.util.StringUtils;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.stream.Collectors;
/**
* 绑定启动网卡或IP的工具类
*
* @author chenjianbo
*/
public final class BindNetAddressUtil {
private static final String CLOUD_BIND_IP_KEY = "--spring.cloud.inetutils.default-ip-address=";
/**
* 获取多网卡IP列表
*
* @param regex 规则,例如:192.168,192.168.8,127.0
* @return IP列表
*/
public static List fetchIP(String regex) {
List address = new ArrayList<>();
try {
Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces();
while (networkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = networkInterfaces.nextElement();
Enumeration inet = networkInterface.getInetAddresses();
while (inet.hasMoreElements()) {
InetAddress inetAddress = inet.nextElement();
if (inetAddress instanceof Inet4Address) {
address.add(inetAddress.getHostAddress());
}
}
}
if (!StringUtils.isEmpty(regex)) {
return address.stream()
.filter(str -> str.contains(regex))
.collect(Collectors.toList());
}
return address;
} catch (SocketException e) {
e.printStackTrace(System.out);
}
return new ArrayList<>();
}
/**
* 初始化SpringCloud初始化绑定的IP问题
*
* @param regex 规则IP
* @param args 参数集合
* @return 环境参数配置
*/
public static String[] initSpringCloudIpEnvironment(String regex, String[] args) {
//处理IP
List addresses = fetchIP(regex);
if (addresses == null || addresses.size() < 1) {
throw new RuntimeException("获取IP失败,启动关闭。");
}
String ip = addresses.listIterator().next();
//处理环境参数
if (args == null) {
throw new RuntimeException("启动参数异常,启动关闭。");
}
boolean k = false;
for (String arg : args) {
if (arg.contains(CLOUD_BIND_IP_KEY)) {
k = true;
break;
}
}
if (k) {
return args;
}
String[] resultArgs = new String[args.length + 1];
System.arraycopy(args, 0, resultArgs, 0, args.length);
resultArgs[resultArgs.length - 1] = CLOUD_BIND_IP_KEY + ip;
return resultArgs;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy