1. 程式人生 > >java筆記----獲取電腦上ip(內網ip)

java筆記----獲取電腦上ip(內網ip)

com nts als site throw str ddr print clas

       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<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; Enumeration
<InetAddress> 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(); }

java筆記----獲取電腦上ip(內網ip)