Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- data class Ip(val node1: Int, val node2: Int, val node3: Int, val node4: Int) : Comparable<Ip> {
- constructor(ipStr: String) {
- val nodesStr = ipStr.split('.')
- if (nodesStr.count() != 4)
- throw InvalidOperationException("Incorrect ip string format")
- val nodes = nodesStr.map { it.toIntOrNull() }.filter { it != null }
- if (nodes.count() != 4)
- throw InvalidOperationException("Some nodes have incorrect format")
- if (!nodes.all { it >= 0 && it <= 255 })
- throw InvalidOperationException("Some nodes great than 255 or less than 0")
- node1 = nodes[0]
- node2 = nodes[1]
- node3 = nodes[2]
- node4 = nodes[3]
- }
- override operator fun compareTo(other: Ip): Int {
- var compare = this.node1 - other.node1
- if (compare != 0) return compare.sign()
- compare = this.node2 - other.node2
- if (compare != 0) return compare.sign()
- compare = this.node3 - other.node3
- if (compare != 0) return compare.sign()
- compare = this.node3 - other.node3
- return compare.sign()
- }
- override operator fun inc(){
- if (node4 < 255)
- return Ip(node1, node2, node3, node4 + 1)
- if (node3 < 255)
- return Ip(node1, node2, node3 + 1, node4)
- if (node2 < 255)
- return Ip(node1, node2 + 1, node3, node4)
- if (node1 < 255)
- return Ip(node1 + 1, node2, node3, node4)
- throw OutOfRangeException("You try increment the max value of Ip (${this})")
- }
- override fun toString(): String {
- return "${node1}.${node2}.${node3}.${node4}"
- }
- }
- fun getIpsByRange(start: Ip, end: Ip): ArrayList<Ip> {
- if (start > end) return emptyList()
- if (start == end) return listOf(start)
- if (end == ++start) return listOf(start, end)
- val resultList = listOf(start)
- var current = start
- while (current < end) {
- resultList.add(++current)
- }
- resultList.add(end)
- return resultList
- }
- fun main(args: Array<String>) {
- if (args.count() != 2) {
- println("Invalid arguments: you need get the two ip for range")
- return
- }
- try {
- getIpsByRange(args[0], args[1]).forEach {
- println(it)
- }
- }
- catch(e: InvalidOperationException | OutOfRangeException) {
- println(e.message)
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement