package com.primeton.damp.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.Inet4Address;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;
/**
*
* 导入 java.net.InetAddress 太保不允许,因此写入到代码里,防止代码扫描工具报安全问题
*
*
* Created by zhenqin.
* User: zhenqin
* Date: 2019/7/18
* Time: 11:02
* Vendor: yiidata.com
* To change this template use File | Settings | File Templates.
*
*
*
* @author zhenqin
*/
public enum NetworkInterfaceManager {
INSTANCE;
private java.net.InetAddress m_local;
private java.net.InetAddress m_localHost;
private static Logger logger = LoggerFactory.getLogger(NetworkInterfaceManager.class);
private NetworkInterfaceManager() {
load();
}
public java.net.InetAddress findValidateIp(List addresses) {
java.net.InetAddress local = null;
int maxWeight = -1;
for (java.net.InetAddress address : addresses) {
if(address instanceof Inet4Address) {
int weight = 0;
if(address.isSiteLocalAddress()) {
weight += 8;
}
if(address.isLinkLocalAddress()) {
weight += 4;
}
if(address.isLoopbackAddress()) {
weight += 2;
}
if(!Objects.equals(address.getHostName(), address.getHostAddress())) {
weight += 1;
}
// 找到权重最大的网卡地址,绑定
if(weight > maxWeight) {
maxWeight = weight;
local = address;
}
}
}
return local;
}
public String getLocalHostAddress() {
return m_local.getHostAddress();
}
public String getLocalHostName() {
try {
if(m_localHost == null) {
m_localHost = java.net.InetAddress.getLocalHost();
}
return m_localHost.getHostName();
} catch (UnknownHostException e) {
return m_local.getHostName();
}
}
private String getProperty(String jvmArg, String envArg) {
String value = System.getenv(envArg);
if(value == null) {
value = System.getProperty(jvmArg);
}
return value;
}
private final void load() {
String ip = getProperty("host.name", "HOST_NAME");
if(ip != null) {
try {
m_local = java.net.InetAddress.getByName(ip);
return;
} catch (UnknownHostException e) {
logger.error("ip 获取异常。", e);
//ignore
}
}
try {
Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
List nis = (interfaces == null) ? Collections.emptyList() : Collections.list(interfaces);
List addresses = new ArrayList<>(nis.size());
java.net.InetAddress local = null;
try {
for (NetworkInterface ni : nis) {
if(ni.isUp() && !ni.isLoopback()) {
addresses.addAll(Collections.list(ni.getInetAddresses()));
}
}
local = findValidateIp(addresses);
} catch (Exception e) {
//ignore
}
if(local != null) {
m_local = local;
return;
}
} catch (SocketException e) {
//ignore except
}
m_local = java.net.InetAddress.getLoopbackAddress();
}
}