Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get user IP in Shiny

Is there a way to get the IP of the person accessing the shiny app? Hopefully there's a R/Shiny solution but I can accept a javascript solution as well. I want to reverse geocode the IP to make graphs that visualize which countries most users access the app from -- and then put that information in the app for all users to see. I only need a way to get the users IP, the other things are easily solveable.

like image 265
ZN13 Avatar asked May 10 '17 09:05

ZN13


2 Answers

You can try this. In the folder www, put this file, say getIP.js:

$(document).ready(function(){
  $.get("http://ipinfo.io", function(response) {
    Shiny.onInputChange("getIP", response);
  }, "json");
});

In ui.R:

shinyUI(fluidPage(
  tags$head(
    tags$script(src="getIP.js")
  ),
  .......

And in server.R (the observer is just for testing):

  IP <- reactive({ input$getIP })

  observe({
    cat(capture.output(str(IP()), split=TRUE))
  })

Then you get such a list as the output of IP() (I hide my IP):

List of 8
 $ ip      : chr "xx MY IP IS HERE xx"
 $ hostname: chr "No Hostname"
 $ city    : chr "Liège"
 $ region  : chr "Wallonia"
 $ country : chr "BE"
 $ loc     : chr "50.6412,5.5718"
 $ org     : chr "AS12392 Brutele SC"
 $ postal  : chr "4020"

This is not perfect, sometimes the result is NULL.

like image 88
Stéphane Laurent Avatar answered Nov 10 '22 07:11

Stéphane Laurent


dont say so much. show code again

library(shiny)  
ui <- fluidPage(
  tags$script('$(document).on("shiny:sessioninitialized",function(){$.get("https://api.ipify.org", function(response) {Shiny.setInputValue("getIP", response);});})'),
  verbatimTextOutput('ip')
)

server <- function(input, output) {
  output$ip <- reactive(input$getIP)
}

shinyApp(ui,server)
like image 23
zhang jing Avatar answered Nov 10 '22 05:11

zhang jing