/** * An IP address (v4 or v6). */ class IPAddress { private var address: Array private var is4: Boolean /** * @throws NumberFormatException if the IP address follows neither the IPv4 syntax, nor the IPv6 syntax. */ constructor(address: String) { val split4 = address.split('.') val split6 = address.split(':') val isV4 = split4.size == 4 && split4.size == split4.filter { it.matches(Regex("^[0-9]$")) }.size val isV6 = split6.size == 16 && split6.size == split6.filter { it.contains(Regex("^[0-9][a-f]$")) }.size if (isV4) { this.is4 = true } else if (isV6) { this.is4 = false } else { throw NumberFormatException() } var bytes: List = if (this.is4) { split4.map { it.toByte(10) } } else { split6.map { it.toByte(16) } } this.address = bytes.toTypedArray() } override fun toString(): String { val str: String if (this.is4) { str = this.address.joinToString(separator = ".") { it.toString() } } else { str = this.address.joinToString(separator = ":") { it.toString() } } return str } }