Skip to content

Instantly share code, notes, and snippets.

@abdalimran
Created October 20, 2016 22:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abdalimran/b9eccb7759d11cf2c2ae2feca391da22 to your computer and use it in GitHub Desktop.
Save abdalimran/b9eccb7759d11cf2c2ae2feca391da22 to your computer and use it in GitHub Desktop.
library(XML)
#Import your list of IPs
ip.addresses <- read.csv("ip-address.csv")
#This is my API
api.url <- "http://freegeoip.net/xml/"
#Appending API URL before each of the IPs
api.with.ip <- paste(api.url, ip.addresses$IP.Addresses ,sep="")
#Creating an empty vector for collecting the country names
country.vec <- c()
#Running a for loop to parse country name for each IP
for(i in api.with.ip)
{
#Using xmlParse & xmlToList to extract IP information
data <- xmlParse(i)
xml.data <- xmlToList(data)
#Selecting only Country Name by using xml.data$CountryName
#If Country Name is NULL then putting NA
if(is.null(xml.data$CountryName)){
country.vec <- c(country.vec, NA)
}
else{
country.vec <- c(country.vec, xml.data$CountryName)
}
}
#Combining IPs with its corresponding country names into a dataframe
result <- data.frame(ip.addresses,country.vec)
colnames(result) <- c("IP Address", "Country")
#Exporting the dataframe as csv file
write.csv(result, "IP_to_Location.csv")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment