summaryrefslogtreecommitdiff
path: root/src/main/kotlin/IPAddress.kt
blob: 1eb69a737de5121063dda87b92cfb0bf3322ecab (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
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
 * An IP address (v4 or v6).
 */
class IPAddress {
    private var address: Array<Byte>
    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(':')

        if (isAddressV4(address)) {
            this.is4 = true
        } else if (isAddressV6(address)) {
            this.is4 = false
        } else {
            throw NumberFormatException()
        }

        var bytes: List<Byte> = if (this.is4) {
            split4.map { it.toByte(10) }
        } else {
            split6.map { it.toByte(16) }
        }
        this.address = bytes.toTypedArray()
    }

    fun isAddressV4(address: String): Boolean {
        val split4 = address.split('.')
        return split4.size == 4 &&
                split4.size == split4.filter { it.matches(Regex("^[0-9]$")) }.size
    }

    fun isAddressV6(address: String): Boolean {
        val split6 = address.split(':')
        return split6.size == 16 &&
                split6.size == split6.filter { it.contains(Regex("^[0-9][a-f]$")) }.size
    }

    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
    }
}