Хотите проверить IPv4-адрес с помощью языка C, но получаете ошибку в количестве точек

#c #validation #ipv4

Вопрос:

вот мой код

 #include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
int main()
{
    int alp=0;
    int ch, spaces;
    char str[30];
    int er=0;
    int dot = 3;
    int cl;
    int i, j, k, l;
    int x;
    int y;
    int z;
    int p;
    printf("Enter IPV4 IP address:");//Enter the IP address
    scanf("%s",amp;str);//For taking input
    char *part;
    char *part1 = strtok(str, ".");
    char *s1 = part1;
    char *part2 = strtok(NULL, ".");
    char *s2 = part2;
    char *part3 = strtok(NULL, ".");
    char *s3 = part3;
    char *part4 = strtok(NULL, ".");
    char *s4 = part4;
    
    if(p < 0 || p > 255)//To check the range of the ip address
    {
       er  ; 
        printf("IP Address not in range");
    }
    if (part4[0]=='0')//to check if the 1st position holds zero
    {
        er  ;
        printf("nZero Found. IP address should not containt leading zero");
        
    }
    if(dot != 3)//to check the separaters
    {
        dot--;
        printf("nValid");
    }
    else
    {
        dot  ;
        printf("nLimit exceeded!! number of dots more than three");
    }
    
    return 0;
}
 

Таким образом, ошибка, которую я получаю, заключается в //для проверки разделителей части моего кода, если я введу 192.168.1.1(действительный IP), показывающий превышение предела ошибок, также если я введу IP с большим количеством точек, показывающих ту же ошибку.

Нужна помощь в этой части моего кода.

Комментарии:

1. Если вы хотите преобразовать / проверить строковое представление адреса IPv4, используйте inet_aton .

2. scanf("%s",amp;str); —> > scanf("%s",str); , хотя понятия не имею, решит ли это вашу проблему.

3. p является неинициализированным, поэтому if(p < 0 || p > 255) является неопределенным

4. у вас есть множество неиспользуемых переменных. Все, что делает, — это добавляет шума и беспорядка. Упростите вещи для себя и избавьтесь от них.

Ответ №1:

Сначала попробуйте мой код с нормальными и ошибочными IP-номерами и понаблюдайте за его выводами. Затем сравните свой код с моим и обнаружьте свои ошибки.

 #include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>

int dotCount(const char* str) {
    int dots = 0;
    while(*str != NULL) {
        if(*str   == '.') dots  ;
    }
    return dots;
}

int main()
{
    char str[30];
    int er=0;
    int dot = 0;
    printf("Enter IPV4 IP address:");//Enter the IP address
    scanf("%s",str);//For taking input
    puts(str);

    // Dot count check
    dot = dotCount(str);
    if(dot == 3)
    {
        printf("nDot count ok");
    }
    else
    {
        er  ;
        printf("nLimit exceeded!! number of dots more than three: %dn", dot);
    }

    char *part;
    part = strtok(str, ".");
    while(part != NULL) {
        dot  ;
//      printf("part: %sn", part); // Part debug
        if(strlen(part) > 1 amp;amp; *part == '0') {
            er  ;
            printf("nZero Found. IP address should not containt leading zero: %sn", part);
        }
        int range = atoi(part);
        if(range < 0 || range > 255)//To check the range of the ip address
        {
            er  ;
            puts("IP Address not in rangen");
        }
        part = strtok(NULL, ".");
    }

    if(er > 0) {
        printf("%d errors foundn",er);
    }
    else {
        puts("No errors foundi IP adress is okn");
    }

    return 0;
}
 

Комментарии:

1. Спасибо! Получил все ошибки, а также знаю, что мой код стал маленьким.