private static String getHostIP(){
String tempIP = "127.0.0.1";
try {
if(isIpv4(InetAddress.getLocalHost().getHostAddress()))
tempIP = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try{
Enumeration networks = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
Enumeration addrs;
while (networks.hasMoreElements())
{
addrs = networks.nextElement().getInetAddresses();
while (addrs.hasMoreElements())
{
ip = addrs.nextElement();
if (ip != null
&& ip instanceof Inet4Address
&& ip.isSiteLocalAddress()
&& !ip.getHostAddress().equals(tempIP))
{ if(isIpv4(ip.getHostAddress()))
return ip.getHostAddress();
}
}
}
return tempIP;
} catch(Exception e){
System.out.println("获取IP地址抛出异常");
throw new RuntimeException(e);
}
}
public static boolean isIpv4(String ipAddress) {
String ip = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
+"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
+"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
+"(00?\\d|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
Pattern pattern = Pattern.compile(ip);
Matcher matcher = pattern.matcher(ipAddress);
return matcher.matches();
}