Problem: to check whether an input string is a valid IPv4 address or IPv6 address or neither.
Tip:要十分注意边界条件,编译了好几次才通过 =.=||
代码:
int toInt(char tmp[], int len) {
int i;
int sum = 0;
if (len > 1 && tmp[len - 1] != '0' && tmp[0] == '0') {//05 or 005 is wrong
return 256;
}
for (i = 0; i < len; i++) {
sum = sum * 10 + (tmp[i] - '0');
}
return sum;
}
int checkIPV4(char *new, int len) {
int i, j, count = 0;
int *transfer = (int *)malloc(4 * sizeof(int)); //If not malloc::: Line 39: store to null pointer of type 'int'
int t = 0;
if (!((new[0] >= '0') && (new[i] <= '9'))) {
return 0;
}
for (i = 0; i < len; i++) {
char tmp[3] = {0};
j = 0;
while ((i < len) && new[i] != '.') {
if (j >= 3) {// in case "6284.56.78.9" or '::::::', for tmp[3] => Line 22: index 3 out of bounds for type 'char [3]'
return 0;
}
if ((new[i] >= '0') && (new[i] <= '9')) {
tmp[j++] = new[i++];
} else {
return 0;
}
}
if (i != len) {
if (new[i] == '.' && new[i - 1] == '.') {return 0;}//in case "12..33.4"
if (new[i] == '.') {count++;}
}
*transfer = toInt(tmp, j);
printf("transfer=%d\n", *transfer);
if (*transfer < 0 || *transfer > 255) {
return 0;
} else {
transfer++;
t++;
}
}
if (count != 3) {
return 0;
}
transfer -= t;
if (transfer[0] == 0 && transfer[1] == 0 && transfer[2] == 0 && transfer[3] == 0) {return 0;}//in case of "00.0.0.0"
return 1;
}
int checkIPV6(char *new, int len) {//"2001:0db8:85a3:0000:0:8A2E:0370:733a"
int i, j, count = 0;
if (!((new[0] >= '0' && new[0] <= '9') || (new[0] >= 'A' && new[0] <= 'F') || (new[0] >= 'a' && new[0] <= 'f'))) {
return 0; //in case "::"
}
for (i = 0; i < len; i++) {
//char tmp[4] = {0};
j = 0;
while (i < len && (new[i] != ':')) {
if (j >= 4) { return 0; }
if ((new[i] >= '0' && new[i] <= '9') || (new[i] >= 'A' && new[i] <= 'F') || (new[i] >= 'a' && new[i] <= 'f')) {
j++;
i++;
} else { return 0; }
}
/*if (j > 1 && tmp[j - 1] != '0' && tmp[0] == '0') {//0AC2 or 035 is right;
return 0;
}*/
if (i != len) {
if (new[i] == ':' && new[i - 1] == ':') { return 0; }//in case "2001::85a3:0000:0:8A2E:0370:733a"
if (new[i] == ':') {count++;}
}
}
printf("count=%d\n", count);
if (count != 7) {
return 0;
}
return 1;
}
char* validIPAddress(char* IP) {
char *ret[3] = {"IPv4", "IPv6", "Neither"};
int len = strlen(IP);
char *new = IP;
int i = 0;
if (len < 7 || len > 39) {
return ret[2];
} else if (len > 15) {
return checkIPV6(new, len) ? ret[1] : ret[2];
} else if (len == 15) { //in case of "f:f:f:f:f:f:f:f"
for (i = 0; i < len; i++) {
if (*(new + i) == ':') {
return checkIPV6(new, len) ? ret[1] : ret[2];
}
}
return checkIPV4(new, len) ? ret[0] : ret[2];
} else {
return checkIPV4(new, len) ? ret[0] : ret[2];
}
}
Submission Detail
79 / 79 test cases passed. | Status: Accepted |
Runtime: 0 ms | Submitted: 2 minutes ago |