To detect if an IP address is a VPN using IP2Location.io in Kotlin, you can use the IP2Location.io API to retrieve geolocation and related data.
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("proxy")) {
if (myobj.getAsJsonObject("proxy").get("is_vpn").asBoolean) {
println("The IP $ip is a VPN.")
} else {
println("The IP $ip is NOT a VPN.")
}
} else {
throw Exception("ERROR: The is_vpn field requires a paid subscription to the Security plan.")
}
} 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)
}
}
This script will check if the specified IP address is a VPN. Make sure to replace 8.8.8.8 with the IP address you want and replace YOUR_API_KEY to your own API key.
Empower your applications with accurate IP geolocation information now.
Try It for Free