Skip to content

Instantly share code, notes, and snippets.

@gutierrezps
Forked from ryantenney/parseIpAddress.java
Last active December 20, 2015 17:39
Show Gist options
  • Save gutierrezps/6170477 to your computer and use it in GitHub Desktop.
Save gutierrezps/6170477 to your computer and use it in GitHub Desktop.
Method to parse IP addresses on format x.x.x.x. Useful for sockets etc.
public static boolean parseIpAddress(String ip) throws IllegalArgumentException { // IPv4, format x.x.x.x
StringTokenizer tok = new StringTokenizer(ip, ".");
if (tok.countTokens() != 4) {
throw new IllegalArgumentException("IP address must be in the format 'xxx.xxx.xxx.xxx'");
}
int i = 0;
while (tok.hasMoreTokens()) {
String strVal = tok.nextToken();
try {
int val = Integer.parseInt(strVal, 10);
if (val < 0 || val > 255) {
throw new IllegalArgumentException("Illegal value '" + val + "' at byte " + (i + 1) + " in the IP address.");
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Illegal value '" + strVal + "' at token " + (i + 1) + " in the IP address.", e);
}
}
return true; // reach here only if no exception occurred
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment