Public IP Capture Program

2

I need to implement in my program a method to capture the public IP of the user ... remembering that this IP must be stored, even before the user establishes any type of connection.

The client running the program should call a method to capture this IP, and it will be stored in a variable within this client ...

How do I proceed?

    
asked by anonymous 20.11.2014 / 01:21

2 answers

4

The most direct way to get your public IP is - as you suggested - access a website that will return this information to you. If there are no drawbacks, why not your own website / application?

But if you need an external service, there are several that you choose - not all so simple to use and / or free (whatismyip.com for example has an API, but only for a paid plan, and with requests limit daily). Here are some options , the simplest and "no frills" being the icanhazip.com (or canihazip.com/s ) - it returns you IP and ready, without html , body , or anything! So to access it just do:

URL url = new URL("http://icanhazip.com/");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String ip = in.readLine();
in.close();

Maybe it's interesting - if your primary source is offline - try some alternative sources. Others that return the raw IP are ifconfig.me/ip and the ipinfo.io/ip (same procedure above).

Source: this question in SOen

    
21.11.2014 / 02:51
0

If it is HTTP, just do the following servlet

package servlet;  

import java.io.IOException;  
import java.io.PrintWriter;  
import javax.servlet.*;  
import javax.servlet.http.*;  

public class ServletIP extends HttpServlet   
{  
   private static final String CONTENT_TYPE = "text/html; charset=ISO-8859-1";  

   public void init(ServletConfig config) throws ServletException  
   {  
      super.init(config);  
   }  

   public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException  
   {  
      response.setContentType(CONTENT_TYPE);  
      PrintWriter out = response.getWriter();  
      out.println(request.getRemoteAddr());  
      out.close();  
   }  
}  

And then the mapping:

<servlet>  
  <servlet-name>ServletIP</servlet-name>  
  <servlet-class>servlet.ServletIP</servlet-class>  
</servlet>  
<servlet-mapping>  
  <servlet-name>ServletIp</servlet-name>  
  <url-pattern>/ip</url-pattern>  
</servlet-mapping>

Loading this on a Java EE server, sending any request to www.ENDERECOWEB / context_con_container / ip, it returns the person's IP address.

    
20.11.2014 / 01:40