public static String getIP() { Enumeration<?> netInterfaces; List<NetworkInterface> netlist=new ArrayList<NetworkInterface>(); try { netInterfaces = NetworkInterface.getNetworkInterfaces();//獲取當前環境下的全部網卡 while (netInterfaces.hasMoreElements()) { NetworkInterface ni=(NetworkInterface)netInterfaces.nextElement(); if(ni.isLoopback()) continue;//過濾 lo網卡 netlist.add(0,ni);//倒置網卡順序 } /* 用上述方法獲取全部網卡時,獲得的順序與服務器中用ifconfig命令看到的網卡順序相反, 所以,想要從第一塊網卡開始遍歷時,須要將Enumeration<?>中的元素倒序 */ for(NetworkInterface list:netlist) { //遍歷每一個網卡 Enumeration<?> cardipaddress = list.getInetAddresses();//獲取網卡下全部ip while(cardipaddress.hasMoreElements()){//將網卡下全部ip地址取出 InetAddress ip = (InetAddress) cardipaddress.nextElement(); if(!ip.isLoopbackAddress()){ if(ip.getHostAddress().equalsIgnoreCase("127.0.0.1")){//guo //return ip.getHostAddress(); continue; } if(ip instanceof Inet6Address) { //過濾ipv6地址 add by liming 2013-9-3 //return ip.getHostAddress(); continue; } if(ip instanceof Inet4Address) { //返回ipv4地址 return ip.getHostAddress(); } } return ip.getLocalHost().getHostAddress();//默認返回 } } } catch (SocketException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return ""; }