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