C++的做法
/* return 1 if string contain only digits, else return 0 */
int valid_digit(char *ip_str)
{
while (*ip_str) {
if (*ip_str >= '0' && *ip_str <= '9')
++ip_str;
else
return 0;
}
return 1;
}
/* return 1 if IP string is valid, else return 0 */
int is_valid_ip(char *ip_str)
{
int i, num, dots = 0;
char *ptr;
if (ip_str == NULL)
return 0;
// See following link for strtok()
// http://pubs.opengroup.org/onlinepubs/009695399/functions/strtok_r.html
ptr = strtok(ip_str, DELIM);
if (ptr == NULL)
return 0;
while (ptr) {
/* after parsing string, it must contain only digits */
if (!valid_digit(ptr))
return 0;
num = atoi(ptr);
/* check for valid IP */
if (num >= 0 && num <= 255) {
/* parse remaining string */
ptr = strtok(NULL, DELIM);
if (ptr != NULL)
++dots;
} else
return 0;
}
/* valid IP string must contain 3 dots */
if (dots != 3)
return 0;
return 1;
}
Java的做法
/* Translated into Java */
public class IPv4Validator {
public static final String DELIM = "\\.";
private boolean isValidIP(String ip) {
if(ip == null || "".equals(ip.trim())) {
return false;
}
String[] parts = ip.split(DELIM);
if(parts.length != 4) {
return false;
}
for(String part : parts) {
try {
int intVal = Integer.parseInt(part);
if(intVal < 0 || intVal > 255) {
return false;
}
} catch(NumberFormatException nfe) {
return false;
}
}
return true;
}
public static void main(String[] args) {
String ip1 = "128.0.0.1";
String ip2 = "125.16.100.1";
String ip3 = "125.512.100.1";
String ip4 = "125.512.100.abc";
String ip5 = " ";
String ip6 = null;
IPv4Validator validator = new IPv4Validator();
System.out.println(validator.isValidIP(ip1));
System.out.println(validator.isValidIP(ip2));
System.out.println(validator.isValidIP(ip3));
System.out.println(validator.isValidIP(ip4));
System.out.println(validator.isValidIP(ip5));
System.out.println(validator.isValidIP(ip6));
}
}