All Downloads are FREE. Search and download functionalities are using the official Maven repository.

codacy.test.NetworkHelper.scala Maven / Gradle / Ivy

The newest version!
package codacy.test

import java.net.{InetAddress, NetworkInterface}

import scala.util.Try

trait NetworkHelper {

  private def notReachableIp(ip: String) =
    (ip.startsWith("localhost") || // not reachable from inside the container
      ip.startsWith("127.0") || // refer to self in the container again
      // ip.startsWith("172.") || // the docker bridge network
      ip.contains(":") // exclude ipv6 addresses
    )

  import scala.jdk.CollectionConverters._

  // trying hard to get one of your public ip addresses
  val hostIp = {
    val ip0 = Try {
      InetAddress.getByName("dockerhost").getHostAddress()
    }.toOption.getOrElse(":")
    if (notReachableIp(ip0)) {
      (for (ifc <- NetworkInterface.getNetworkInterfaces().asScala) yield {
        if (ifc.isUp() && !ifc.isPointToPoint())
          ifc.getInetAddresses().asScala.map(_.getHostAddress()).toSeq
        else Seq()
      }).flatten.find(!notReachableIp(_)).get
    } else ip0
  }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy