其他分享
首页 > 其他分享> > Util

Util

作者:互联网

/**
* 获取本地IP
*
* @return 本地IP
*/
public static String getLocalHostIP() {
  String localHostIP = "";
  try {
    Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
    if (interfaces != null) {
      while (interfaces.hasMoreElements()) {
        NetworkInterface currentNetwork = interfaces.nextElement();
        if (!currentNetwork.isUp() || currentNetwork.isLoopback() || currentNetwork.isVirtual()) {
          continue;
        }
        Enumeration<InetAddress> addresses = currentNetwork.getInetAddresses();
        while (addresses.hasMoreElements()) {
          InetAddress currentAddr = addresses.nextElement();
          if (currentAddr.isLoopbackAddress()) {
            continue;
          }
          if (currentAddr instanceof Inet4Address) {
            localHostIP = currentAddr.getHostAddress();
          }
        }
      }
    }
  } catch (SocketException e) {
    LOGGER.error(e.getMessage(), e);
  }
  return localHostIP;
}

 

标签:addresses,hasMoreElements,currentNetwork,interfaces,currentAddr,Util,localHostIP
来源: https://www.cnblogs.com/chengshentao/p/14869761.html