Last active
May 20, 2020 16:52
-
-
Save frgomes/b4da5e0b87305c1c4c1352df87e13e26 to your computer and use it in GitHub Desktop.
Scala - Obtain FQDN
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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