def findLocalInetAddress()

in flink-connector-netty/src/main/scala/org/apache/flink/streaming/connectors/netty/example/NettyUtil.scala [35:68]


  def findLocalInetAddress(): InetAddress = {

    val address = InetAddress.getLocalHost
    address.isLoopbackAddress match {
      case true =>
        // Address resolves to something like 127.0.1.1, which happens on Debian; try to find
        // a better address using the local network interfaces
        // getNetworkInterfaces returns ifs in reverse order compared to ifconfig output order
        // on unix-like system. On windows, it returns in index order.
        // It's more proper to pick ip address following system output order.
        val activeNetworkIFs = NetworkInterface.getNetworkInterfaces.asScala.toSeq
        val reOrderedNetworkIFs = SystemUtils.IS_OS_WINDOWS match {
          case true => activeNetworkIFs
          case false => activeNetworkIFs.reverse
        }

        reOrderedNetworkIFs.find { ni: NetworkInterface =>
          val addr = ni.getInetAddresses.asScala.toSeq.filterNot { addr =>
            addr.isLinkLocalAddress || addr.isLoopbackAddress
          }
          addr.nonEmpty
        } match {
          case Some(ni) =>
            val addr = ni.getInetAddresses.asScala.toSeq.filterNot { inet =>
              inet.isLinkLocalAddress || inet.isLoopbackAddress
            }
            val address = addr.find(_.isInstanceOf[Inet4Address]).getOrElse(addr.head).getAddress
            // because of Inet6Address.toHostName may add interface at the end if it knows about it
            InetAddress.getByAddress(address)
          case None => address
        }
      case false => address
    }
  }