Created
November 9, 2015 10:54
-
-
Save SriramKeerthi/cc12e7e26ed102d03ea1 to your computer and use it in GitHub Desktop.
Fetches the public IP of the machine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.net.InetAddress; | |
import java.net.NetworkInterface; | |
import java.net.SocketException; | |
import java.util.ArrayList; | |
import java.util.Enumeration; | |
import java.util.List; | |
public class IPUtil | |
{ | |
/** | |
* Returns true if the ip is private IP | |
* @param ip | |
* @return | |
*/ | |
public static boolean isPrivateIP( String ip ) | |
{ | |
boolean local = ip.startsWith( "192.168." ) || ip.startsWith( "10." ); | |
if ( local ) { | |
return true; | |
} else { | |
if ( ip.startsWith( "172." ) ) { | |
Integer second = Integer.parseInt( ip.split( "\\." )[1] ); | |
if ( second >= 16 && second <= 31 ) { | |
return true; | |
} | |
} | |
} | |
return false; | |
} | |
public static boolean isLocalHost( String ip ) | |
{ | |
return "127.0.0.1".equals( ip ); | |
} | |
/** | |
* Returns the most 'public' IP | |
* @return | |
* @throws SocketException | |
*/ | |
public static String getIP() throws SocketException | |
{ | |
Enumeration e = NetworkInterface.getNetworkInterfaces(); | |
List<String> allIPs = new ArrayList<>(); | |
while ( e.hasMoreElements() ) { | |
NetworkInterface n = (NetworkInterface) e.nextElement(); | |
Enumeration ee = n.getInetAddresses(); | |
while ( ee.hasMoreElements() ) { | |
InetAddress i = (InetAddress) ee.nextElement(); | |
allIPs.add( i.getHostAddress() ); | |
} | |
} | |
for ( String ip : allIPs ) { | |
if ( isPrivateIP( ip ) || isLocalHost( ip ) ) { | |
continue; | |
} | |
// Return the first non-private, non-localhost ip | |
return ip; | |
} | |
// If no public IP is found, return the first private IP | |
for ( String ip : allIPs ) { | |
if ( isLocalHost( ip ) ) { | |
continue; | |
} | |
// Return the first non-private, non-localhost ip | |
return ip; | |
} | |
// If nothing else works, return localhost | |
return "127.0.0.1"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment