Last active
December 21, 2017 17:38
-
-
Save sergiocasero/685c076f35b366d532959897f4e8ed93 to your computer and use it in GitHub Desktop.
Simple code to get your public ip address
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import IpAddress.Companion.IP_END | |
import IpAddress.Companion.IP_SEGMENT_SIZE | |
import IpAddress.Companion.IP_START | |
import kotlinx.coroutines.experimental.runBlocking | |
import java.net.URL | |
/** | |
* Ipfy | |
*/ | |
data class IpAddress(private val segment1: Int, | |
private val segment2: Int, | |
private val segment3: Int, | |
private val segment4: Int) { | |
companion object { | |
val SEGMENT_SEPARATOR = "." | |
val IP_SEGMENT_SIZE = 4 | |
val CLASS_A_START = 0 | |
val CLASS_A_END = 127 | |
val CLASS_B_START = 128 | |
val CLASS_B_END = 191 | |
val CLASS_C_START = 192 | |
val CLASS_C_END = 223 | |
val IP_START = 0 | |
val IP_END = 255 | |
} | |
val type: Type = when (segment1) { | |
in CLASS_A_START..CLASS_A_END -> Type.CLASS_A | |
in CLASS_B_START..CLASS_B_END -> Type.CLASS_B | |
in CLASS_C_START..CLASS_C_END -> Type.CLASS_C | |
else -> { | |
throw InvalidIpAddressException() | |
} | |
} | |
enum class Type { | |
CLASS_A, CLASS_B, CLASS_C | |
} | |
override fun toString(): String = "$segment1.$segment2.$segment3.$segment4" | |
} | |
class InvalidIpAddressException(message: String = "Invalid IP, the format must be XXX.XXX.XXX.XXX") : Exception(message) | |
fun stringToIp(text: String): IpAddress { | |
val segments = text.split(IpAddress.SEGMENT_SEPARATOR) | |
val invalidSegments = segments.filter { it.toIntOrNull() == null || it.toInt() !in IP_START..IP_END }.count() | |
if (invalidSegments > 0 || segments.size != IP_SEGMENT_SIZE) { | |
throw InvalidIpAddressException() | |
} | |
return IpAddress(segments[0].toInt(), segments[1].toInt(), segments[2].toInt(), segments[3].toInt()) | |
} | |
suspend fun callIpfy(): IpAddress = stringToIp(URL("https://api.ipify.org?format=text").readText()) | |
fun main(args: Array<String>) { | |
runBlocking { | |
val ip = callIpfy() | |
println(ip) | |
when (ip.type) { | |
IpAddress.Type.CLASS_A -> println("class A!!") | |
IpAddress.Type.CLASS_B -> println("class B!!") | |
IpAddress.Type.CLASS_C -> println("class C!!") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment