summaryrefslogtreecommitdiff
path: root/src/main/kotlin/IPAddress.kt
blob: 206a8b63d9ad8038be41f30e671b1e92f456a666 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
 * An IP address (v4 or v6).
 */
class IPAddress {
    private var address4: Array<Byte> = Array(4) { 0 }
    private var address6: Array<Byte> = Array(16) { 0 }
    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<Byte> = emptyList()

        if (split4.size == 4) {
            bytes = split4.map { it.toByte() }
            this.address4 = bytes.toTypedArray()
            this.is4 = true
        } else if (split6.size == 16) {
            bytes = split4.map { it.toByte(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
    }
}