Java準確地獲取本地IP地址

問題

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

1. 多塊網卡。spa

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

看似簡單的代碼,寫起來仍是要當心一些的。blog

方案

HBase客戶端獲取本機IP的代碼提供了一個很好的參考。沒有特殊需求的話,拷貝過去用吧:)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);
  }
相關文章
相關標籤/搜索