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;
}

 

上一篇:ROS2学习之旅(20)——创建一个动作消息


下一篇:详解C++STL容器系列(三)—— map属性和方法详解