java.net.NetworkInterface Scala Examples
The following examples show how to use java.net.NetworkInterface.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: MockHttpServer.scala From cornichon with Apache License 2.0 | 6 votes |
package com.github.agourlay.cornichon.http.server import java.net.NetworkInterface import com.github.agourlay.cornichon.core.CornichonError import monix.eval.Task import monix.execution.Scheduler import org.http4s.HttpRoutes import org.http4s.server.Router import org.http4s.server.blaze.BlazeServerBuilder import org.http4s.implicits._ import scala.jdk.CollectionConverters._ import scala.concurrent.duration._ import scala.util.Random class MockHttpServer[A](interface: Option[String], port: Option[Range], mockService: HttpRoutes[Task], maxRetries: Int = 5)(useFromAddress: String => Task[A])(implicit scheduler: Scheduler) { private val selectedInterface = interface.getOrElse(bestInterface()) private val randomPortOrder = port.fold(0 :: Nil)(r => Random.shuffle(r.toList)) private val mockRouter = Router("/" -> mockService).orNotFound def useServer(): Task[A] = if (randomPortOrder.isEmpty) Task.raiseError(MockHttpServerError.toException) else startServerTryPorts(randomPortOrder) private def startServerTryPorts(ports: List[Int], retry: Int = 0): Task[A] = startBlazeServer(ports.head).onErrorHandleWith { case _: java.net.BindException if ports.length > 1 => startServerTryPorts(ports.tail, retry) case _: java.net.BindException if retry < maxRetries => val sleepFor = retry + 1 println(s"Could not start server on any port. Retrying in $sleepFor seconds...") startServerTryPorts(randomPortOrder, retry = retry + 1).delayExecution(sleepFor.seconds) } private def startBlazeServer(port: Int): Task[A] = BlazeServerBuilder[Task](executionContext = scheduler) .bindHttp(port, selectedInterface) .withoutBanner .withHttpApp(mockRouter) .withNio2(true) .resource .use(server => useFromAddress(s"http://${server.address.getHostString}:${server.address.getPort}")) private def bestInterface(): String = NetworkInterface.getNetworkInterfaces.asScala .filter(_.isUp) .flatMap(_.getInetAddresses.asScala) .find(_.isSiteLocalAddress) .map(_.getHostAddress) .getOrElse("localhost") } case object MockHttpServerError extends CornichonError { val baseErrorMessage = "the range of ports provided for the HTTP mock is invalid" }
Example 2
Source File: DockerUtils.scala From drizzle-spark with Apache License 2.0 | 5 votes |
package org.apache.spark.util import java.net.{Inet4Address, InetAddress, NetworkInterface} import scala.collection.JavaConverters._ import scala.sys.process._ import scala.util.Try private[spark] object DockerUtils { def getDockerIp(): String = { def findFromDockerMachine(): Option[String] = { sys.env.get("DOCKER_MACHINE_NAME").flatMap { name => Try(Seq("/bin/bash", "-c", s"docker-machine ip $name 2>/dev/null").!!.trim).toOption } } sys.env.get("DOCKER_IP") .orElse(findFromDockerMachine()) .orElse(Try(Seq("/bin/bash", "-c", "boot2docker ip 2>/dev/null").!!.trim).toOption) .getOrElse { // This block of code is based on Utils.findLocalInetAddress(), but is modified to blacklist // certain interfaces. val address = InetAddress.getLocalHost // 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 blackListedIFs = Seq( "vboxnet0", // Mac "docker0" // Linux ) val activeNetworkIFs = NetworkInterface.getNetworkInterfaces.asScala.toSeq.filter { i => !blackListedIFs.contains(i.getName) } val reOrderedNetworkIFs = activeNetworkIFs.reverse for (ni <- reOrderedNetworkIFs) { val addresses = ni.getInetAddresses.asScala .filterNot(addr => addr.isLinkLocalAddress || addr.isLoopbackAddress).toSeq if (addresses.nonEmpty) { val addr = addresses.find(_.isInstanceOf[Inet4Address]).getOrElse(addresses.head) // because of Inet6Address.toHostName may add interface at the end if it knows about it val strippedAddress = InetAddress.getByAddress(addr.getAddress) return strippedAddress.getHostAddress } } address.getHostAddress } } }
Example 3
Source File: SystemInfo.scala From slide-desktop with GNU General Public License v2.0 | 5 votes |
package slide import java.net.NetworkInterface import enums.OperatingSystem object SystemInfo { private val os: String = System.getProperty("os.name").toUpperCase var operatingSystem: OperatingSystem = OperatingSystem.UNKNOWN var systemExtension: String = "" var chmod: String = "+x" if (os.toUpperCase.contains("WIN")) { chmod = "" systemExtension = ".exe" operatingSystem = OperatingSystem.WINDOWS } else if (os.toUpperCase.contains("MAC")) operatingSystem = OperatingSystem.OSX else operatingSystem = OperatingSystem.NIX def isNetworkIsAvailable: Boolean = { val interfaces: java.util.Enumeration[NetworkInterface] = NetworkInterface.getNetworkInterfaces while (interfaces.hasMoreElements) { val interf: NetworkInterface = interfaces.nextElement() if (interf.isUp && !interf.isLoopback) return true } false } }
Example 4
Source File: HttpUpload.scala From temperature-machine with Apache License 2.0 | 5 votes |
package bad.robot.temperature.client import java.net.{InetAddress, NetworkInterface} import bad.robot.temperature.IpAddress._ import bad.robot.temperature._ import cats.effect.IO import org.http4s.Status.Successful import org.http4s.Uri.{Authority, IPv4, Scheme} import org.http4s.client.dsl.Http4sClientDsl.WithBodyOps import org.http4s.client.{Client => Http4sClient} import org.http4s.dsl.io._ import org.http4s.headers.`X-Forwarded-For` import org.http4s.{Uri, _} import scalaz.{-\/, \/, \/-} import scala.collection.JavaConverters._ case class HttpUpload(address: InetAddress, client: Http4sClient[IO]) extends TemperatureWriter { private implicit val encoder = jsonEncoder[Measurement] private val decoder = EntityDecoder.text[IO] def write(measurement: Measurement): Error \/ Unit = { val uri = Uri( scheme = Some(Scheme.http), authority = Some(Authority(host = IPv4(address.getHostAddress), port = Some(11900))), path = "/temperature" ) val request: IO[Request[IO]] = PUT.apply(uri, measurement, `X-Forwarded-For`(currentIpAddress)) val fetch: IO[Error \/ Unit] = client.fetch(request) { case Successful(_) => IO.pure(\/-(())) case error @ _ => IO(-\/(UnexpectedError(s"Failed to PUT temperature data to ${uri.renderString}, response was ${error.status}: ${error.as[String](implicitly, decoder).attempt.unsafeRunSync}"))) } // why no leftMap? fetch.attempt.map { case Left(t) => -\/(UnexpectedError(s"Failed attempting to connect to $address to send $measurement\n\nError was: $t")) case Right(value) => value }.unsafeRunSync() } } object HttpUpload { val allNetworkInterfaces: List[NetworkInterface] = { NetworkInterface.getNetworkInterfaces .asScala .toList .filter(_.isUp) .filterNot(_.isLoopback) } }
Example 5
Source File: DockerUtils.scala From sparkoscope with Apache License 2.0 | 5 votes |
package org.apache.spark.util import java.net.{Inet4Address, InetAddress, NetworkInterface} import scala.collection.JavaConverters._ import scala.sys.process._ import scala.util.Try private[spark] object DockerUtils { def getDockerIp(): String = { def findFromDockerMachine(): Option[String] = { sys.env.get("DOCKER_MACHINE_NAME").flatMap { name => Try(Seq("/bin/bash", "-c", s"docker-machine ip $name 2>/dev/null").!!.trim).toOption } } sys.env.get("DOCKER_IP") .orElse(findFromDockerMachine()) .orElse(Try(Seq("/bin/bash", "-c", "boot2docker ip 2>/dev/null").!!.trim).toOption) .getOrElse { // This block of code is based on Utils.findLocalInetAddress(), but is modified to blacklist // certain interfaces. val address = InetAddress.getLocalHost // 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 blackListedIFs = Seq( "vboxnet0", // Mac "docker0" // Linux ) val activeNetworkIFs = NetworkInterface.getNetworkInterfaces.asScala.toSeq.filter { i => !blackListedIFs.contains(i.getName) } val reOrderedNetworkIFs = activeNetworkIFs.reverse for (ni <- reOrderedNetworkIFs) { val addresses = ni.getInetAddresses.asScala .filterNot(addr => addr.isLinkLocalAddress || addr.isLoopbackAddress).toSeq if (addresses.nonEmpty) { val addr = addresses.find(_.isInstanceOf[Inet4Address]).getOrElse(addresses.head) // because of Inet6Address.toHostName may add interface at the end if it knows about it val strippedAddress = InetAddress.getByAddress(addr.getAddress) return strippedAddress.getHostAddress } } address.getHostAddress } } }
Example 6
Source File: AsyncEcsDiscovery.scala From akka-management with Apache License 2.0 | 5 votes |
package akka.discovery.awsapi.ecs import java.net.{ InetAddress, NetworkInterface } import scala.collection.JavaConverters._ import akka.annotation.ApiMayChange @ApiMayChange object AsyncEcsDiscovery { // InetAddress.getLocalHost.getHostAddress throws an exception when running // in awsvpc mode because the container name cannot be resolved. // ECS provides a metadata file // (https://docs.aws.amazon.com/AmazonECS/latest/developerguide/container-metadata.html) // that we ought to be able to use instead to find our IP address, but the // metadata file does not get set when running on Fargate. So this is our // only option for determining what the canonical Akka and akka-management // hostname values should be set to. def getContainerAddress: Either[String, InetAddress] = NetworkInterface.getNetworkInterfaces.asScala .flatMap(_.getInetAddresses.asScala) .filterNot(_.isLoopbackAddress) .filter(_.isSiteLocalAddress) .toList match { case List(value) => Right(value) case other => Left(s"Exactly one private address must be configured (found: $other).") } }
Example 7
Source File: DockerUtils.scala From multi-tenancy-spark with Apache License 2.0 | 5 votes |
package org.apache.spark.util import java.net.{Inet4Address, InetAddress, NetworkInterface} import scala.collection.JavaConverters._ import scala.sys.process._ import scala.util.Try private[spark] object DockerUtils { def getDockerIp(): String = { def findFromDockerMachine(): Option[String] = { sys.env.get("DOCKER_MACHINE_NAME").flatMap { name => Try(Seq("/bin/bash", "-c", s"docker-machine ip $name 2>/dev/null").!!.trim).toOption } } sys.env.get("DOCKER_IP") .orElse(findFromDockerMachine()) .orElse(Try(Seq("/bin/bash", "-c", "boot2docker ip 2>/dev/null").!!.trim).toOption) .getOrElse { // This block of code is based on Utils.findLocalInetAddress(), but is modified to blacklist // certain interfaces. val address = InetAddress.getLocalHost // 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 blackListedIFs = Seq( "vboxnet0", // Mac "docker0" // Linux ) val activeNetworkIFs = NetworkInterface.getNetworkInterfaces.asScala.toSeq.filter { i => !blackListedIFs.contains(i.getName) } val reOrderedNetworkIFs = activeNetworkIFs.reverse for (ni <- reOrderedNetworkIFs) { val addresses = ni.getInetAddresses.asScala .filterNot(addr => addr.isLinkLocalAddress || addr.isLoopbackAddress).toSeq if (addresses.nonEmpty) { val addr = addresses.find(_.isInstanceOf[Inet4Address]).getOrElse(addresses.head) // because of Inet6Address.toHostName may add interface at the end if it knows about it val strippedAddress = InetAddress.getByAddress(addr.getAddress) return strippedAddress.getHostAddress } } address.getHostAddress } } }
Example 8
Source File: HostAddressResolver.scala From seahorse with Apache License 2.0 | 5 votes |
package ai.deepsense.workflowexecutor.executor import java.net.{Inet6Address, InetAddress, NetworkInterface} import scala.util.Try import ai.deepsense.commons.utils.Logging object HostAddressResolver extends Logging { def findHostAddress(): InetAddress = { import collection.JavaConversions._ Try { val interfaces = NetworkInterface.getNetworkInterfaces.toIterable interfaces.flatMap { n => n.getInetAddresses.toIterable.filter { address => !address.isInstanceOf[Inet6Address] && !address.isLoopbackAddress && !address.isSiteLocalAddress && !address.isLinkLocalAddress && !address.isAnyLocalAddress && !address.isMulticastAddress && !(address.getHostAddress == "255.255.255.255") } } }.get.headOption.getOrElse(InetAddress.getByName("127.0.0.1")) } }
Example 9
Source File: HostAddressResolver.scala From seahorse with Apache License 2.0 | 5 votes |
package ai.deepsense.sessionmanager.service import java.net.{Inet6Address, InetAddress, NetworkInterface} import scala.util.Try import ai.deepsense.commons.utils.Logging object HostAddressResolver extends Logging { def getHostAddress(): String = { val address = if (System.getenv("MANAGED_BY") == "TAP") { logger.info("Getting host address from environment") getHostAddressFromEnv() } else { logger.info("Getting host address from network interface") getHostAddressFromInterface() } logger.info(s"Host address: $address") address } private def getHostAddressFromInterface(): String = { import collection.JavaConversions._ Try { val interfaces = NetworkInterface.getNetworkInterfaces.toIterable interfaces.flatMap { n => n.getInetAddresses.toIterable.filter { address => !address.isInstanceOf[Inet6Address] && !address.isLoopbackAddress && !address.isLinkLocalAddress && !address.isAnyLocalAddress && !address.isMulticastAddress && !(address.getHostAddress == "255.255.255.255") } } }.get.headOption.getOrElse(InetAddress.getByName("127.0.0.1")).getHostAddress } private def getHostAddressFromEnv(): String = { val hostname = System.getenv("HOSTNAME") val podId = hostname.toUpperCase.split("-").head val clusterIp = System.getenv(s"${podId}_SERVICE_HOST") clusterIp } }
Example 10
Source File: NetUtils.scala From mist with Apache License 2.0 | 5 votes |
package io.hydrosphere.mist.utils import java.net.{Inet4Address, InetAddress, NetworkInterface} import scala.collection.JavaConverters._ object NetUtils { def findLocalInetAddress(): InetAddress = { val address = InetAddress.getLocalHost if (address.isLoopbackAddress) { val activeNetworkIFs = NetworkInterface.getNetworkInterfaces.asScala.toList.reverse for (ni <- activeNetworkIFs) { val addresses = ni.getInetAddresses.asScala.toList .filterNot(addr => addr.isLinkLocalAddress || addr.isLoopbackAddress) if (addresses.nonEmpty) { val addr = addresses.find(_.isInstanceOf[Inet4Address]).getOrElse(addresses.head) val strippedAddress = InetAddress.getByAddress(addr.getAddress) return strippedAddress } } } address } }
Example 11
Source File: DockerUtils.scala From Spark-2.3.1 with Apache License 2.0 | 5 votes |
package org.apache.spark.util import java.net.{Inet4Address, InetAddress, NetworkInterface} import scala.collection.JavaConverters._ import scala.sys.process._ import scala.util.Try private[spark] object DockerUtils { def getDockerIp(): String = { def findFromDockerMachine(): Option[String] = { sys.env.get("DOCKER_MACHINE_NAME").flatMap { name => Try(Seq("/bin/bash", "-c", s"docker-machine ip $name 2>/dev/null").!!.trim).toOption } } sys.env.get("DOCKER_IP") .orElse(findFromDockerMachine()) .orElse(Try(Seq("/bin/bash", "-c", "boot2docker ip 2>/dev/null").!!.trim).toOption) .getOrElse { // This block of code is based on Utils.findLocalInetAddress(), but is modified to blacklist // certain interfaces. val address = InetAddress.getLocalHost // 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 blackListedIFs = Seq( "vboxnet0", // Mac "docker0" // Linux ) val activeNetworkIFs = NetworkInterface.getNetworkInterfaces.asScala.toSeq.filter { i => !blackListedIFs.contains(i.getName) } val reOrderedNetworkIFs = activeNetworkIFs.reverse for (ni <- reOrderedNetworkIFs) { val addresses = ni.getInetAddresses.asScala .filterNot(addr => addr.isLinkLocalAddress || addr.isLoopbackAddress).toSeq if (addresses.nonEmpty) { val addr = addresses.find(_.isInstanceOf[Inet4Address]).getOrElse(addresses.head) // because of Inet6Address.toHostName may add interface at the end if it knows about it val strippedAddress = InetAddress.getByAddress(addr.getAddress) return strippedAddress.getHostAddress } } address.getHostAddress } } }
Example 12
Source File: DockerUtils.scala From BigDatalog with Apache License 2.0 | 5 votes |
package org.apache.spark.util import java.net.{Inet4Address, NetworkInterface, InetAddress} import scala.collection.JavaConverters._ import scala.sys.process._ import scala.util.Try private[spark] object DockerUtils { def getDockerIp(): String = { def findFromDockerMachine(): Option[String] = { sys.env.get("DOCKER_MACHINE_NAME").flatMap { name => Try(Seq("/bin/bash", "-c", s"docker-machine ip $name 2>/dev/null").!!.trim).toOption } } sys.env.get("DOCKER_IP") .orElse(findFromDockerMachine()) .orElse(Try(Seq("/bin/bash", "-c", "boot2docker ip 2>/dev/null").!!.trim).toOption) .getOrElse { // This block of code is based on Utils.findLocalInetAddress(), but is modified to blacklist // certain interfaces. val address = InetAddress.getLocalHost // 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 blackListedIFs = Seq( "vboxnet0", // Mac "docker0" // Linux ) val activeNetworkIFs = NetworkInterface.getNetworkInterfaces.asScala.toSeq.filter { i => !blackListedIFs.contains(i.getName) } val reOrderedNetworkIFs = activeNetworkIFs.reverse for (ni <- reOrderedNetworkIFs) { val addresses = ni.getInetAddresses.asScala .filterNot(addr => addr.isLinkLocalAddress || addr.isLoopbackAddress).toSeq if (addresses.nonEmpty) { val addr = addresses.find(_.isInstanceOf[Inet4Address]).getOrElse(addresses.head) // because of Inet6Address.toHostName may add interface at the end if it knows about it val strippedAddress = InetAddress.getByAddress(addr.getAddress) return strippedAddress.getHostAddress } } address.getHostAddress } } }
Example 13
Source File: NetworkUtils.scala From asura with MIT License | 5 votes |
package asura.common.util import java.net.{InetAddress, NetworkInterface} import scala.collection.JavaConverters._ object NetworkUtils { def getLocalIpAddress(): String = { val interfaces = NetworkInterface.getNetworkInterfaces.asScala.toSeq val ipAddresses = interfaces.flatMap(_.getInetAddresses.asScala.toSeq) val address = ipAddresses.find(address => { val host = address.getHostAddress host.contains(".") && !address.isLoopbackAddress }).getOrElse(InetAddress.getLocalHost) address.getHostAddress } }
Example 14
Source File: BindAddress.scala From zipkin-mesos-framework with Apache License 2.0 | 5 votes |
package net.elodina.mesos.zipkin.utils import java.net.{Inet4Address, InetAddress, NetworkInterface} import java.util import scala.collection.JavaConversions._ class BindAddress(s: String) { private var _source: String = null private var _value: String = null def source: String = _source def value: String = _value parse() def parse() = { val idx = s.indexOf(":") if (idx != -1) { _source = s.substring(0, idx) _value = s.substring(idx + 1) } else { _value = s } if (source != null && source != "if") throw new IllegalArgumentException(s) } def resolve(): String = { _source match { case null => resolveAddress(_value) case "if" => resolveInterfaceAddress(_value) case _ => throw new IllegalStateException("Failed to resolve " + s) } } def resolveAddress(addressOrMask: String): String = { if (!addressOrMask.endsWith("*")) return addressOrMask val prefix = addressOrMask.substring(0, addressOrMask.length - 1) for (ni <- NetworkInterface.getNetworkInterfaces) { val address = ni.getInetAddresses.find(_.getHostAddress.startsWith(prefix)).orNull if (address != null) return address.getHostAddress } throw new IllegalStateException("Failed to resolve " + s) } def resolveInterfaceAddress(name: String): String = { val ni = NetworkInterface.getNetworkInterfaces.find(_.getName == name).orNull if (ni == null) throw new IllegalStateException("Failed to resolve " + s) val addresses: util.Enumeration[InetAddress] = ni.getInetAddresses val address = addresses.find(_.isInstanceOf[Inet4Address]).orNull if (address != null) return address.getHostAddress throw new IllegalStateException("Failed to resolve " + s) } override def hashCode(): Int = 31 * _source.hashCode + _value.hashCode override def equals(o: scala.Any): Boolean = { if (o == null || o.getClass != this.getClass) return false val address = o.asInstanceOf[BindAddress] _source == address._source && _value == address._value } override def toString: String = s }
Example 15
Source File: HostAddressResolver.scala From seahorse-workflow-executor with Apache License 2.0 | 5 votes |
package io.deepsense.workflowexecutor.executor import java.net.{Inet6Address, InetAddress, NetworkInterface} import scala.util.Try import io.deepsense.commons.utils.Logging object HostAddressResolver extends Logging { def findHostAddress(): InetAddress = { import collection.JavaConversions._ Try { val interfaces = NetworkInterface.getNetworkInterfaces.toIterable interfaces.flatMap { n => n.getInetAddresses.toIterable.filter { address => !address.isInstanceOf[Inet6Address] && !address.isLoopbackAddress && !address.isSiteLocalAddress && !address.isLinkLocalAddress && !address.isAnyLocalAddress && !address.isMulticastAddress && !(address.getHostAddress == "255.255.255.255") } } }.get.headOption.getOrElse(InetAddress.getByName("127.0.0.1")) } }