Mega Code Archive

 
Categories / Java / Network Protocol
 

Finds this computers global IP address

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.Inet4Address; import java.net.InetAddress; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class Util{   /**    * Finds this computer's global IP address    *     * @return The global IP address, or null if a problem occurred    */   public static Inet4Address getGlobalAddress()   {     try     {       URLConnection uc = new URL( "http://www.whatismyip.org/" ).openConnection();       BufferedReader br = new BufferedReader( new InputStreamReader( uc.getInputStream() ) );       return ( Inet4Address ) InetAddress.getByName( br.readLine() );     }     catch( MalformedURLException e )     {       e.printStackTrace();     }     catch( IOException e )     {       e.printStackTrace();     }     return null;   } }