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();
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM