Last active
June 22, 2021 02:09
-
-
Save frgomes/f562f1c90f9bcdca387af5cd1c6d0e9d to your computer and use it in GitHub Desktop.
Scala - Pattern match extractors, Regex domain names, IPv4, IPv6
This file contains hidden or 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
/** Parse any IPv4 address or IPv6 address or domain name */ | |
def parsePeerAddress(value: String): Try[String] = | |
parseIPv4(value) orElse parseIPv6(value) orElse parseHostname(value) | |
/** Parse IPv4 address */ | |
def parseIPv4(value: String): Try[String] = | |
value.trim match { | |
case regexIPv4(_*) => Success(value) | |
case _ => Failure(new IllegalArgumentException(s"invalid IPv4 address name: ${value.trim}")) | |
} | |
/** Parse IPv6 address */ | |
def parseIPv6(value: String): Try[String] = | |
value.trim.toUpperCase match { | |
case regexIPv6(_*) => Success(value) | |
case _ => Failure(new IllegalArgumentException(s"invalid IPv4 address name: ${value.trim}")) | |
} | |
/** Performs a DNS query, trying to resolve hostname. */ | |
def parseHostname(hostname: String): Try[String] = { | |
def checkEmpty(hostname: String): Try[String] = | |
if(hostname.length == 0) Failure(new java.net.UnknownHostException()) else Success(hostname) | |
def resolve(hostname: String): Try[String] = | |
Try { java.net.InetAddress.getByName(hostname).toString } | |
def checkInvalid(address: String): Try[String] = | |
if(address.startsWith("/")) Failure(new java.net.UnknownHostException(address)) else Success(address) | |
checkEmpty(hostname.trim) | |
.flatMap(resolve) | |
.flatMap(checkInvalid) | |
} | |
//credits: Regular Expressions Cookbook by Steven Levithan, Jan Goyvaerts | |
/** Regular expression which matches a IPv4 address */ | |
val regexIPv4 = "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$".r | |
//credits: Regular Expressions Cookbook by Steven Levithan, Jan Goyvaerts | |
/** Regular expression which matches a IPv6 address */ | |
val regexIPv6 = "^(?:(?:(?:[A-F0-9]{1,4}:){6}|(?=(?:[A-F0-9]{0,4}:){0,6}(?:[0-9]{1,3}\\.){3}[0-9]{1,3}$)(([0-9A-F]{1,4}:){0,5}|:)((:[0-9A-F]{1,4}){1,5}:|:))(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)|(?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4}|(?=(?:[A-F0-9]{0,4}:){0,7}[A-F0-9]{0,4}$)(([0-9A-F]{1,4}:){1,7}|:)((:[0-9A-F]{1,4}){1,7}|:))$".r |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment