您的位置:首页 > 编程语言 > Java开发

获取本机IP可区分系统可区分虚拟机和本机java程序跨平台

2013-09-12 21:44 441 查看
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 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: