Java code to find public IP address (servlet and client side code)


Java code to find public IP address :

URL url= new URL("http://gt-tests.appspot.com/ip");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String ip = in.readLine();
System.out.println("IP : "+ip);

I created a simple servlet app on google app engine  and posted at http://gt-tests.appspot.com/ip .

The servlet code returns the public address of client, it looks like :

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  PrintWriter out = resp.getWriter();
  // Get client's IP address
  String addr = req.getRemoteAddr();
  out.println(addr);
  ...

2 comments :

  1. i didn't understand how it works..

    ReplyDelete
    Replies
    1. Hi GlamFather,
      The logic is simple, I have a webapp that have the servlet code as mentioned above which is running in google appspot server,
      And each time you send a request to the server as

      URL url= new URL("http://gt-tests.appspot.com/ip");

      And we read the server reply from this code :

      BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
      String ipAddress = in.readLine();

      and you get remote address (public Ip) of your PC as seen by the application.

      I hope its clear now.

      Delete

Your Comment and Question will help to make this blog better...