How can I identify the ISP associated with an IP address in Kotlin?

To determine the ISP of an IP address using IP2Location.io in Kotlin, you can use the IP2Location.io API to retrieve geolocation and related data.

  1. We'll assume that you have already installed an IDE like IntelliJ that supports Kotlin and we won't cover that here. You will also need a paid subscription to the Starter plan or higher. Subscribe now!
  2. In your IDE, create a new Kotlin project. Then, add Kotlinx Coroutines Core and Gson into your project.
  3. Save the below code into a file called Test.kt on your computer.
    Kotlin
    
    import com.google.gson.*
    import kotlinx.coroutines.*
    import kotlinx.coroutines.future.await
    import java.net.URI
    import java.net.http.HttpClient
    import java.net.http.HttpRequest
    import java.net.http.HttpResponse
    
    @Throws(Exception::class)
    fun main() {
        try {
            val ip = "8.8.8.8"
            val key = "YOUR_API_KEY"
            val url = "https://api.ip2location.io?format=json&key=$key&ip=$ip"
            val request: HttpRequest = HttpRequest.newBuilder().uri(URI(url)).GET().build()
            val client = HttpClient.newHttpClient()
            runBlocking {
                val response = client.sendAsync(request, HttpResponse.BodyHandlers.ofString()).await()
    
                val statusCode = response.statusCode()
                if (statusCode == 200) {
                    val rawJSON = response.body()
                    val myobj = JsonParser.parseString(rawJSON).asJsonObject
                    if (myobj.has("isp")) {
                        println("The ISP for IP $ip is ${myobj.get("isp").asString}.")
                    } else {
                        throw Exception("ERROR: The isp field requires a paid subscription to the Starter plan or higher.")
                    }
                } else if (statusCode == 400 || statusCode == 401) {
                    val rawJSON = response.body()
                    if (rawJSON.contains("error_message")) {
                        throw Exception(
                            "ERROR: ${
                                JsonParser.parseString(rawJSON).asJsonObject.getAsJsonObject("error")
                                    .get("error_message").asString
                            }."
                        )
                    }
                    throw Exception(rawJSON)
                } else {
                    throw Exception(response.body())
                }
            }
        } catch (e: Exception) {
            println(e)
        }
    }
    			
  4. In the IDE, run the Test.kt file.

This script will output the ISP of specified IP address. Make sure to replace 8.8.8.8 with the IP address you want and replace YOUR_API_KEY to your own API key.

Other Languages

Unlock Location Insights For Free

Empower your applications with accurate IP geolocation information now.

Try It for Free