Created
July 23, 2012 15:48
-
-
Save ryantenney/3164334 to your computer and use it in GitHub Desktop.
Parsing an IP Address in Java
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 InetAddress parseIpAddress(String ip) throws IllegalArgumentException { | |
StringTokenizer tok = new StringTokenizer(ip, "."); | |
if (tok.countTokens() != 4) { | |
throw new IllegalArgumentException("IP address must be in the format 'xxx.xxx.xxx.xxx'"); | |
} | |
byte[] data = new byte[4]; | |
int i = 0; | |
while (tok.hasMoreTokens()) { | |
String strVal = tok.nextToken(); | |
try { | |
int val = Integer.parseInt(tok.nextToken(), 10); | |
if (val < 0 || val > 255) { | |
throw new IllegalArgumentException("Illegal value '" + val + "' at byte " + (i + 1) + " in the IP address."); | |
} | |
data[i++] = (byte) Integer.parseInt(tok.nextToken(), 10); | |
} catch (NumberFormatException e) { | |
throw new IllegalArgumentException("Illegal value '" + strVal + "' at token " + (i + 1) + " in the IP address.", e); | |
} | |
} | |
try { | |
return InetAddress.getByAddress(ip, data); | |
} catch (UnknownHostException e) { | |
// This actually can't happen since the method InetAddress.getByAddress(String, byte[]) | |
// doesn't perform any lookups and we have already guaranteed that the length of data is 4 | |
throw new Error("UnknownHostException somehow thrown when creating an InetAddress", e); | |
} | |
} |
inside while()
loop, on lines 13 and 19, change tok.nextToken()
to strVal
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This code cannot possibly work: calling Integer.parseInt(tok.nextToken()) will advance to the next token, skipping the one it should be working on. Author obviously never tested this code.