Skip to content

Instantly share code, notes, and snippets.

@frgomes
Last active May 20, 2020 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save frgomes/b4da5e0b87305c1c4c1352df87e13e26 to your computer and use it in GitHub Desktop.
Save frgomes/b4da5e0b87305c1c4c1352df87e13e26 to your computer and use it in GitHub Desktop.
Scala - Obtain FQDN
def fqdn: Option[String] = {
val marker = "domain "
def ipv4(canonical: String): Boolean = {
def isAllDigits(x: String) = x forall Character.isDigit
canonical != null && !canonical.isEmpty && {
val parts = canonical.split('.')
parts.length > 1 && !parts.map(part => isAllDigits(part)).reduce(_ & _)
}
}
val addr: java.net.InetAddress = java.net.InetAddress.getLocalHost
val hostname: String = addr.getHostName
val canonical: String = addr.getCanonicalHostName
if(ipv4(canonical)) Some(canonical)
else {
val is: java.io.InputStream = new java.io.FileInputStream(new java.io.File("/etc/resolv.conf"))
val lines = scala.io.Source.fromInputStream(is).getLines.toStream
val domains: Seq[String] = lines.filter(line => line.startsWith(marker)).map(line => line.substring(marker.length).trim)
if(domains.size == 0) None
else {
val domain = domains(0)
Some(s"${hostname}.${domain}")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment