1、只是Windows系统使用的
InetAddress addr = InetAddress.getLocalHost();
String ip=addr.getHostAddress().toString;//获得本机IP
String address=addr.getHostName().toString;//获得本机名称
2、windows和linux都可以使用的,且只获取IPV4,返回String类型
public class GetLocalHostAddr {
public String getLocalHostAddr(){
Enumeration allNetInterfaces;
Vector<String> ipAddr = new Vector<String>();
String ipLocalAddr = null;
InetAddress ip = null;
try {
allNetInterfaces = NetworkInterface.getNetworkInterfaces();
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface)
allNetInterfaces.nextElement();
System.out.println(netInterface.getName()+”====Name”);
Enumeration addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = (InetAddress) addresses.nextElement();
ipAddr.add(ip.toString());
if (ip != null && ip instanceof Inet4Address) //IP是ipv4,ipv6换成Inet6Address
{
String hostAddress = ip.getHostAddress();
System.out.println("本机的IP =" + hostAddress);
System.out.println("hostAddress===="+hostAddress.equals("127.0.0.1"));
if(!hostAddress.equals("127.0.0.1") && !hostAddress.equals("/127.0.0.1")){ ipLocalAddr = ip.toString().split("[/]")[1]; //得到本地IP
}
System.out.println(ipLocalAddr+"===============ipLocalAddr");
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
return ipLocalAddr;
}
3、Windows上区分虚拟机和本机的IP
判断时加上netInterface.getName()==eth0 (本机IP) netInterface.getName()==eth1 (虚拟机IP)(一个虚拟机)
4、分辨系统(通过系统名字)
String osName = System.getProperty("os.name"); //获取系统名称
if(osName!=null&&osName.startsWith("Windows")){ //如果是Windows系统
//获取IP
}esle if(osName!=null&&osName.startsWith("Linux")){ //如果是Linux系统
//获取IP }