-
-
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.
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
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