获取本机的IP地址(去除127.0.0.1)
/**
* Created by zhangyan on 2017/8/31.
*/
public class IpTool {
private static final Logger LOG = Logger.getLogger(IpTool.class);
public static String getLocalInet4Address() throws BaseException{
try {
Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ipAddress = null;
String ip = null;
while (allNetInterfaces.hasMoreElements())
{
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
//System.out.println(netInterface.getName());
Enumeration addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements())
{
ipAddress = (InetAddress) addresses.nextElement();
if (ipAddress != null && ipAddress instanceof Inet4Address)
{
if( ipAddress.getHostAddress().equals("127.0.0.1")){
continue;
}else{
ip = ipAddress.getHostAddress();
System.out.println("本机的IP = " + ipAddress.getHostAddress());
}
}
}
}
return ip;
} catch (SocketException e) {
LOG.error("【IpTool.getLocalInet4Address】获取IP地址异常");
throw new BaseException(Code.GET_IP_ERROR);
}
}
}