Determine if a string is a valid IPv4 address in C

后端 未结 15 2036
感情败类
感情败类 2020-12-24 08:22

What would be a good way to determine if a string contains an IPv4 address? Should I use isdigit()?

15条回答
  •  死守一世寂寞
    2020-12-24 08:39

    I'll give the "don't want two problems" solution:

    #include 
    
    
    
    int isIp_v4( char* ip){
            int num;
            int flag = 1;
            int counter=0;
            char* p = strtok(ip,".");
    
            while (p && flag ){
                    num = atoi(p);
    
                    if (num>=0 && num<=255 && (counter++<4)){
                            flag=1;
                            p=strtok(NULL,".");
    
                    }
                    else{
                            flag=0;
                            break;
                    }
            }
    
            return flag && (counter==3);
    
    }
    

    EDIT: strtok may not be thread safe (credits to Adam Rosenfield)

提交回复
热议问题