ipv4的ip字符串转化为int型

时间:2019-10-31
本文章向大家介绍ipv4的ip字符串转化为int型,主要包括ipv4的ip字符串转化为int型使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

要求:

  将现有一个ipv4的ip字符串(仅包含数字,点,空格), 其中数字和点之间的空格(至多一个)是合法的,比如“12 .3. 4 .62”,其他情况均为非法地址。写一个函数将ipv4地址字符串转化成32位整数。

实现:

#include<stdio.h>
#include<string.h>

int is_digit(char ch)
{
    if(ch>='0' && ch<='9')
        return 1;
    return 0;
}

int ipv4_to_int(char* str, int* part)
{
    int len=0,index=0,i=0;
    char* ps=str;

    if(ps == NULL)
        return -1;

    len=strlen(ps);
    if(len<7 || len >21)
        return -1;
    
    if(!is_digit(ps[0]) || !is_digit(ps[len-1]) )
        return -1;

    part[index]=part[index]*10+(int)(ps[0]-'0');
    
    for(i=1;i<len-1;i++){
        char ch = ps[i];
        if(is_digit(ch)){
            part[index]=part[index]*10+(int)(ch-'0');
            if(part[index]>255)
                return -1;
        }
        else if(ch==' ')
        {
            if( (is_digit(ps[i-1]) && ps[i+1]=='.') || \
                (ps[i-1]=='.' && is_digit(ps[i+1])) )
                continue;
            else
                return -1;
        }
        else if(ch=='.')
        {
            if( (is_digit(ps[i-1]) || ps[i-1]==' ') && \
                (ps[i+1]==' ' || is_digit(ps[i+1])) )
            {
                index++;
                if(index>3)
                    return -1;
            }
            else
                return -1;
        }
        else
            return -1;
    }

    part[index]=part[index]*10+(int)(ps[i]-'0');
    if(part[index]>255)
        return -1;

    return 0;
}

int main(int argc, char *argv[])
{
    char exm[16][30]={
        "255.255.255.255",
        "0.0.0.0",
        "12 .3. 4 .56",
        {},
        "2.3..",
        "121 . 234 . 114 . 115.",
        ".12.4.7.7",
        "123.34.55.",
        "1.3.5.4.2.4",
        " 123.3.4.5",        
        "123.45.67.67 ",
           "12 3. 45.67.  67",    
           "12.256.0.1",
           "A1.34.45.6",
           "34.56.-2.5",
           ". . .",
    };

    int part[4]={0,0,0,0};
    int j=0;
    for(j=0;j<15;j++){
        if(!ipv4_to_int(exm[j], part))
            printf("ip_addr: %30s    is <OK>    ====> %d.%d.%d.%d\n",exm[j], part[0],part[1],part[2],part[3]);
        else
            printf("ip_addr: %30s    is Invalid !!!\n",exm[j]);
        
        part[0]=part[1]=part[2]=part[3]=0;
    }
    return 0;
}

欢迎大家批评指正!!     :-)

原文地址:https://www.cnblogs.com/savionyin/p/11770905.html