top.hmtools.system.IPTools Maven / Gradle / Ivy
package top.hmtools.system;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
* ip地址工具
* @author HyboJ
* 创建日期:2017-1-3下午9:47:41
*/
public class IPTools {
/**
* 获取本机的所有IP地址(适用于多个网卡时)
* @return
*/
public static List getLocalIps(){
List result = new ArrayList();
try {
Enumeration interfaces=null;
interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface ni = interfaces.nextElement();
Enumeration addresss = ni.getInetAddresses();
while(addresss.hasMoreElements())
{
InetAddress nextElement = addresss.nextElement();
String hostAddress = nextElement.getHostAddress();
result.add(hostAddress);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 获取本机IP地址(适用于单个网卡时)
* @return
*/
@SuppressWarnings("static-access")
public static String getLocalIp(){
String result = "";
InetAddress ia=null;
try {
ia=ia.getLocalHost();
result=ia.getHostAddress();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 获取本机 机器名称
* @return
*/
@SuppressWarnings("static-access")
public static String getLocalHostName(){
String result = "";
InetAddress ia=null;
try {
ia=ia.getLocalHost();
result=ia.getHostName();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}