zoukankan      html  css  js  c++  java
  • 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);
      }
  • 相关阅读:
    AS3 判断双击事件
    php 数据类型转换与比较
    几行几列算法
    CCNode的属性说明
    bitmapdata的知识点
    addFrameScript用法
    TweenMax.allTo
    flash TweenMax用法
    flash流媒体资料
    c实现windows socket
  • 原文地址:https://www.cnblogs.com/ohuang/p/5780375.html
Copyright © 2011-2022 走看看