R语言 如何使用R查找IP地址信息

R语言 如何使用R查找IP地址信息

在这篇文章中,我们将使用IPinfo API来提取IP信息。

IPinfo是一个免费的API,用来获取特定IP地址的信息,如他们的位置。我们将使用httr GET()来进行URL请求并将数据存储在一个变量中。现在我们需要JSON数据,所以我们必须将数据转换成char格式,因为GET()返回原始数据,所以我们需要使用rawToChar(),为了将char数据转换成JSON格式,我们将使用内置的jsonlite包fromJSON()。

注意: 如果你已经安装了软件包,你不需要在脚本中包括install.package()。

例子

# installing required packages
install.packages("httr")
install.packages("jsonlite")
 
# importing packages/libraries
library(httr)
library(jsonlite)
 
# storing url in a variable
# you can also pass the url directly in GET()
url1 = "https://ipinfo.io/161.185.160.93/geo"
 
# requesting raw data from URL using GET()
# and storing in data variable.
data <- GET(url1)
 
# converting raw data to char format.
rawdata <- rawToChar(datacontent)
 
# converting char data to json format.
jsondata <- fromJSON(rawdata)
 
# printing output
# we are using cat() instead of print function
# so that we can use new line
cat(paste("IP:", jsondataip,"\nCITY:",
          jsondatacity,"\nRegion:",
          jsondataregion,"\nCOUNTRY:",
          jsondatacountry,"\nCOORDINATES:",
          jsondataloc))
Bash

输出

IP: 161.185.160.93

CITY: New York City

Region: New York

COUNTRY: US

COORDINATES: 40.7143,-74.0060
Bash

例子:从用户那里手动获取输入信息

为了获得用户的输入,我们将使用readline(),并使用as.character()将其转换为字符。现在我们将使用paste0()来完成URL,并将其传递给GET()函数。

# installing required packages
install.packages("httr")
install.packages("jsonlite")
 
# importing packages/libraries
library(httr)
library(jsonlite)
 
# storing incomplete url in a variable
url = "https://ipinfo.io/"
 
# manually taking ip as a input from user
ip = readline("Enter your IP address:")
 
# converting input ip address to character
ip = as.character(ip)
 
# completing url
url1 = paste0(url,ip,"/geo")
 
# requesting raw data from URL using GET()
# and string in rawdata variable.
rawdata <- GET(url1)
 
# converting raw data to char format.
chardata <- rawToChar(rawdatacontent)
 
# converting char data to json format.
jsondata <- fromJSON(chardata)
 
# printing output
# we are using cat() instead of print function
# so that we can use new line
cat(paste("IP:", jsondataip,"\nCITY:",
          jsondatacity,"\nRegion:",
          jsondataregion,"\nCOUNTRY:",
          jsondatacountry,"\nCOORDINATES:",
          jsondataloc))
Bash

输出

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
Bash

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册