多网卡下获取本机IP的方式。
方式一:
public class NetworkUtils {
public static final String localHostIp = "127.0.0.1";
public static final String LOCALHOST = "localhost";
public static String currentIp = null;
public static String getLocalInetAddress() {
try {
if (!StringUtil.isBlank(currentIp)){
return currentIp;
}
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface ni = interfaces.nextElement();
Enumeration<InetAddress> addresses = ni.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress address = addresses.nextElement();
if (!address.isLoopbackAddress() && !address.getHostAddress().contains(":")) {
currentIp = address.getHostAddress();
return address.getHostAddress();
}
}
}
} catch (SocketException e) {
log.error("获取本地IP 失败:" + e);
}
return localHostIp;
}
}
方式二:
private static String getInetAddress()
{
try
{
//取得本机的所有网卡
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
InetAddress address = null;
while (interfaces.hasMoreElements())
{
NetworkInterface ni = interfaces.nextElement();
Enumeration<InetAddress> addresses = ni.getInetAddresses();
while (addresses.hasMoreElements())
{
address = addresses.nextElement();
//仅仅取第一个网卡的IP地址就直接返回, 如果是多个网卡只返回第一个网卡的IP地址
if (!address.isLoopbackAddress() && address.getHostAddress().indexOf(":") == -1)
{
return address.getHostAddress();
}
}
}
logger.warn("[InetAddressUtil] Can not get the server IP address.");
return null;
}
catch (Throwable t)
{
logger.warn("[InetAddressUtil] Get the server IP address failed.", t);
return null;
}
}