Skip to content

Instantly share code, notes, and snippets.

@JaHIY
Created September 16, 2012 08:33
Show Gist options
  • Save JaHIY/3731591 to your computer and use it in GitHub Desktop.
Save JaHIY/3731591 to your computer and use it in GitHub Desktop.
C:if it is a valid ipv4 address
#include <stdio.h>
#include <string.h>
int is_valid_ipv4(const char *str) {
int tmp = 0, dot = 0, digit = 0, i = 0;
size_t len = strlen(str) + 1;
while (i < len) {
//printf("%s, %d\n", str, tmp);
if (*str < 48 || *str > 57) {
if (*str == '.' || *str == '\0') {
if (tmp < 0 || tmp > 255) {
return 2;
} else {
if (digit == 0) {
if (*str == '\0') {
return 5;
} else {
return 4;
}
} else {
tmp = 0;
digit = 0;
if (*str == '.') {
dot++;
}
}
}
} else {
return 1;
}
} else {
tmp = tmp*10 + (*str) - 48;
digit++;
}
str++, i++;
}
if (dot < 1 || dot > 3) {
return 3;
}
return 0;
}
int main(int argc, char *argv[]) {
int i;
for (i=1; i<argc; i++) {
switch (is_valid_ipv4(argv[i])) {
case 0:
printf("\"%s\" is valid IPv4 address.\n", argv[i]);
break;
case 1:
printf("Error: \"%s\" is invalid!\n", argv[i]);
break;
case 2:
printf("Error: \"%s\" is out of range!\n", argv[i]);
break;
case 3:
printf("Error: \".\" in \"%s\" are more or less than THREE!\n", argv[i]);
break;
case 4:
printf("Error: one \".\" in \"%s\" is adjacent to another!\n", argv[i]);
break;
case 5:
printf("Error: \"%s\" need more decimal!\n", argv[i]);
break;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment