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);
  }
相关文章
相关标签/搜索