package getlocalip;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.*;
public class GetLocalIpUtil {
private static Set<String> machineIps = Collections.synchronizedSet(new HashSet<String>());
public static Set<String> get() {
if (!machineIps.isEmpty()) {
return machineIps;
}
try {
InetAddress[] addresses = getAllLocalUsingNetworkInterface();
if (addresses == null || addresses.length == 0) {
System.out.println("定时器本机可用的ip地址失败,getAllLocalUsingNetworkInterface返回0个地址");
return machineIps;
}
for (InetAddress address : addresses) {
if (!address.getHostAddress().toString().equals("127.0.0.1")) {
machineIps.add(address.getHostAddress().toString());
}
}
System.out.println("定时器本机可用的ip地址成功,ip地址:" + machineIps.toString());
} catch (UnknownHostException e) {
System.out.println("获取定时器物理IP失败!message={}" + e.getMessage());
}
return machineIps;
}
private static InetAddress[] getAllLocalUsingNetworkInterface() throws UnknownHostException {
List<Object> addresses = new ArrayList<Object>();
Enumeration<NetworkInterface> e = null;
try {
e = NetworkInterface.getNetworkInterfaces();
} catch (SocketException ex) {
throw new UnknownHostException("127.0.0.1");
}
while (e.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) e.nextElement();
for (Enumeration<InetAddress> e2 = ni.getInetAddresses(); e2.hasMoreElements();) {
addresses.add(e2.nextElement());
}
}
InetAddress[] iAddresses = new InetAddress[addresses.size()];
for (int i = 0; i < iAddresses.length; i++) {
iAddresses[i] = (InetAddress) addresses.get(i);
}
return iAddresses;
}
}