From 5a2c35806d78d12d60d49511af2da6a21a91964b Mon Sep 17 00:00:00 2001 From: Edoardo La Greca Date: Wed, 18 Jun 2025 19:14:50 +0200 Subject: add all source code --- src/main/kotlin/IPAddress.kt | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 src/main/kotlin/IPAddress.kt (limited to 'src/main/kotlin/IPAddress.kt') diff --git a/src/main/kotlin/IPAddress.kt b/src/main/kotlin/IPAddress.kt new file mode 100644 index 0000000..91226f5 --- /dev/null +++ b/src/main/kotlin/IPAddress.kt @@ -0,0 +1,39 @@ +/** + * An IP address (v4 or v6). + */ +class IPAddress { + private var address4: Array = Array(4) { 0u } + private var address6: Array = Array(16) { 0u } + 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(':') + var bytes: List = emptyList() + + if (split4.size == 4) { + bytes = split4.map { it.toUByte() } + this.address4 = bytes.toTypedArray() + this.is4 = true + } else if (split6.size == 16) { + bytes = split4.map { it.toUByte(16) } + this.address6 = bytes.toTypedArray() + this.is4 = false + } else { + throw NumberFormatException() + } + } + + override fun toString(): String { + val str: String + if (this.is4) { + str = address4.joinToString(separator = ".") { it.toString() } + } else { + str = address6.joinToString(separator = ":") { it.toString() } + } + return str + } +} \ No newline at end of file -- cgit v1.2.3