Linux下用Java获取本机IP
可能有多个网卡包括虚拟网卡,需要进行排除
String ip = ""; try { Enumeration<?> e1 = NetworkInterface.getNetworkInterfaces();//获取多个网卡 while (e1.hasMoreElements()) { NetworkInterface ni = (NetworkInterface) e1.nextElement(); if(("eth0").equals(ni.getName()) || ("ens33").equals(ni.getName())){//取“eth0”和“ens33”两个网卡 Enumeration<?> e2 = ni.getInetAddresses(); while (e2.hasMoreElements()) { InetAddress ia = (InetAddress) e2.nextElement(); if (ia instanceof Inet6Address) {//排除IPv6地址 continue; } ip = ia.getHostAddress(); } break; } } } catch (SocketException e) { e.printStackTrace(); }