How to find IP address information using R
Last Updated :
25 Mar, 2022
In this article, we will be extracting IP information using IPinfo API.
IPinfo is a free API that is used to get information on specific IP addresses such as their location. We will be using httr GET() to make URL requests and store data in a variable. Now we will need JSON data so we have to convert the data into char format because GET() returns raw data so we will need to use rawToChar() and to convert char data in JSON format we will be using fromJSON() built-in jsonlite package.
Note: You need not include install.package() in the script if you already have the package installed.
Example:
R
install.packages ( "httr" )
install.packages ( "jsonlite" )
library (httr)
library (jsonlite)
data <- GET (url1)
rawdata <- rawToChar (data$content)
jsondata <- fromJSON (rawdata)
cat ( paste ( "IP:" , jsondata$ip, "\nCITY:" ,
jsondata$city, "\nRegion:" ,
jsondata$region, "\nCOUNTRY:" ,
jsondata$country, "\nCOORDINATES:" ,
jsondata$loc))
|
Output:
IP: 161.185.160.93
CITY: New York City
Region: New York
COUNTRY: US
COORDINATES: 40.7143,-74.0060
Example: Getting input manually from the user
To get input from the user we will be readline() and convert it in character using as.character(). Now we will use paste0() to complete the URL and pass it in GET() function.
R
install.packages ( "httr" )
install.packages ( "jsonlite" )
library (httr)
library (jsonlite)
ip = readline ( "Enter your IP address:" )
ip = as.character (ip)
url1 = paste0 (url,ip, "/geo" )
rawdata <- GET (url1)
chardata <- rawToChar (rawdata$content)
jsondata <- fromJSON (chardata)
cat ( paste ( "IP:" , jsondata$ip, "\nCITY:" ,
jsondata$city, "\nRegion:" ,
jsondata$region, "\nCOUNTRY:" ,
jsondata$country, "\nCOORDINATES:" ,
jsondata$loc))
|
Output:
Enter your IP address:161.185.160.93
IP: 161.185.160.93
CITY: New York City
Region: New York
COUNTRY: US
COORDINATES: 40.7143,-74.0060
Share your thoughts in the comments
Please Login to comment...