Java准確地獲取本地IP地址


問題

用Java獲取本機IP地址,需要處理:

1. 多塊網卡。

2. 排除loopback設備、虛擬網卡

看似簡單的代碼,寫起來還是要小心一些的。

方案

HBase客戶端獲取本機IP的代碼提供了一個很好的參考。沒有特殊需求的話,拷貝過去用吧:)

// From HBase Addressing.Java
private static InetAddress getIpAddress(AddressSelectionCondition condition) throws
      SocketException {
    // Before we connect somewhere, we cannot be sure about what we'd be bound to; however,
    // we only connect when the message where client ID is, is long constructed. Thus,
    // just use whichever IP address we can find.
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    while (interfaces.hasMoreElements()) {
      NetworkInterface current = interfaces.nextElement();
      if (!current.isUp() || current.isLoopback() || current.isVirtual()) continue;
      Enumeration<InetAddress> addresses = current.getInetAddresses();
      while (addresses.hasMoreElements()) {
        InetAddress addr = addresses.nextElement();
        if (addr.isLoopbackAddress()) continue;
        if (condition.isAcceptableAddress(addr)) {
          return addr;
        }
      }
    }

    throw new SocketException("Can't get our ip address, interfaces are: " + interfaces);
  }

 


免責聲明!

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



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