public static String getPublicIPAddress ( ) throws Exception { final String IPV4_REGEX = "\\A(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}\\z" ; String ipAddr = null ; Enumeration e = NetworkInterface . getNetworkInterfaces ( ) ; while ( e . hasMoreElements ( ) ) { NetworkInterface n = ( NetworkInterface ) e . nextElement ( ) ; Enumeration ee = n . getInetAddresses ( ) ; while ( ee . hasMoreElements ( ) ) { InetAddress i = ( InetAddress ) ee . nextElement ( ) ; // Pick the first non loop back address if ( ( ! i . isLoopbackAddress ( ) && i . isSiteLocalAddress ( ) ) || i . getHostAddress ( ) . matches ( IPV4_REGEX ) ) { ipAddr = i . getHostAddress ( ) ; break ; } } if ( ipAddr != null ) { break ; } } return ipAddr ; }
This function returns the first external IP address encountered