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

To detect if an IP address is a VPN using IP2Location.io in Ruby, you can use the IP2Location.io API to retrieve geolocation and related data.

  1. We'll assume that you have already installed Ruby and we won't cover that here. You will also need a paid subscription to the Security plan. Subscribe now!
  2. Save the below code into a file called test.rb on your computer.
    Ruby
    
    require 'net/http'
    require 'json'
    
    key = 'YOUR_API_KEY'
    ip = '8.8.8.8'
    
    uri = URI('https://api.ip2location.io/')
    params = { :key => key, :ip => ip }
    uri.query = URI.encode_www_form(params)
    
    res = Net::HTTP.get_response(uri)
    
    if !res.body.nil?
    	begin
    		myobj = JSON.parse(res.body)
    		if res.is_a?(Net::HTTPSuccess)
    			if myobj.key? 'proxy'
    				if myobj['proxy']['is_vpn']
    					puts 'The IP ' + ip + ' is a VPN.'
    				else
    					puts 'The IP ' + ip + ' is NOT a VPN.'
    				end
    			else
    				puts 'ERROR: The is_vpn field requires a paid subscription to the Security plan.'
    			end
    		else
    			if res.body.include? 'error_message'
    				puts 'ERROR: ' + myobj['error']['error_message']
    			else
    				puts 'ERROR: ' + res.body
    			end
    		end
    	rescue JSON::ParserError
    		puts 'ERROR: Invalid JSON in response.'
    	end
    else
    	puts 'ERROR: Error calling API.'
    end
    			
  3. In the command line, run the below command.
    Bash
    
    ruby test.rb
    			

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