My program takes several arguments, one of which has to be an IP address to specify which server it should be trying to connect to. Is there an easy way to check whether the argument the program has been given can be expressed as an IP address?
Asked
Active
Viewed 5,646 times
3 Answers
4
Use a regex to match your ip address:
^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$
I believe that there is a related answer here.
Excerpt:
private static final String PATTERN =
"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
"([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
public static boolean validate(final String ip){
Pattern pattern = Pattern.compile(PATTERN);
Matcher matcher = pattern.matcher(ip);
return matcher.matches();
}

Community
- 1
- 1

Adam Arold
- 29,285
- 22
- 112
- 207
-
1That does, of course, match things like `976.888.421.634`. *Edit* - The edit addresses that. – T.J. Crowder Mar 24 '14 at 15:58
1
The reliable way is to use Guava's InetAddresses.isInetAddress()
method.
Otherwise you can test using a regex to crudely match a dotted quad decimal form (ie, ^\d{1,3}(\.\d{1,3}){3}$
and then test with:
InetAddress.getByName(yourInputString)
that the address is well formed (this method will not do any name resolution if its string argument is an IP literal, it will just check its syntax).
Note that Guava's method has the advantage that it does IPv6.

fge
- 119,121
- 33
- 254
- 329