How can I use an API to detect if an IP address is a VPN in Scala?

To detect if an IP address is a VPN using IP2Location.io in Scala, 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 Scala and we won't cover that here. You will also need a paid subscription to the Security plan. Subscribe now!
  2. In your IDE, create a new Scala project. Then, add Gson into your project.
  3. Save the below code into a file called Test.scala on your computer.
    Scala
    
    import com.google.gson.*
    import java.net.URI
    import java.net.http.{HttpClient, HttpRequest, HttpResponse}
    
    @main def Test(): Unit = {
      try {
        val key = "YOUR_API_KEY"
        val ip = "8.8.8.8"
    
        val url = "https://api.ip2location.io/?format=json&key=" + key + "&ip=" + ip
        val request = HttpRequest.newBuilder.uri(new URI(url)).GET.build
        val client = HttpClient.newHttpClient
        val response = client.sendAsync(request, HttpResponse.BodyHandlers.ofString).join()
        val statusCode = response.statusCode()
        if (statusCode == 200) {
          val rawJSON = response.body()
          val myObj = JsonParser.parseString(rawJSON).getAsJsonObject
          if (myObj.has("proxy")) {
            if (myObj.getAsJsonObject("proxy").get("is_vpn").getAsBoolean) {
              System.out.println("The IP " + ip + " is a VPN.")
            }
            else {
              System.out.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).getAsJsonObject.getAsJsonObject("error")
              .get("error_message").getAsString
            )
          }
          throw Exception(rawJSON)
        } else {
          throw Exception(response.body())
        }
      } catch {
        case e: Exception => System.out.println(e)
      }
    }
    			
  4. In the IDE, run the Test.scala file.

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.

Other Languages

Unlock Location Insights For Free

Empower your applications with accurate IP geolocation information now.

Try It for Free