AlanGomes

Untitled

Mar 24th, 2015
245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.34 KB | None | 0 0
  1. protected String getIP()
  2.     {
  3.         // This try will give the Public IP Address of the Host.
  4.         try
  5.         {
  6.             URL url = new URL("http://automation.whatismyip.com/n09230945.asp");
  7.             BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
  8.             String ipAddress = new String();
  9.             ipAddress = (in.readLine()).trim();
  10.             /* IF not connected to internet, then
  11.              * the above code will return one empty
  12.              * String, we can check it's length and
  13.              * if length is not greater than zero,
  14.              * then we can go for LAN IP or Local IP
  15.              * or PRIVATE IP
  16.              */
  17.             if (!(ipAddress.length() > 0))
  18.             {
  19.                 try
  20.                 {
  21.                     InetAddress ip = InetAddress.getLocalHost();
  22.                     return ((ip.getHostAddress()).trim());
  23.                 }
  24.                 catch(Exception ex)
  25.                 {
  26.                     return "ERROR";
  27.                 }
  28.             }
  29.  
  30.             return (ipAddress);
  31.         }
  32.         catch(Exception e)
  33.         {
  34.             // This try will give the Private IP of the Host.
  35.             try
  36.             {
  37.                 InetAddress ip = InetAddress.getLocalHost();
  38.                 return ((ip.getHostAddress()).trim());
  39.             }
  40.             catch(Exception ex)
  41.             {
  42.                 return "ERROR";
  43.             }
  44.         }
  45.     }
Advertisement
Add Comment
Please, Sign In to add comment