c/c++语言开发共享ipv4的ip字符串转化为int型

要求: 将现有一个ipv4的ip字符串(仅包含数字,点,空格), 其中数字和点之间的空格(至多一个)是合法的,比如“12 .3. 4 .62”,其他情况均为非法地址。写一个函数将ipv4地址字符串转化成int整数(只能遍历一遍字符串)。 实现思路: 1. 安全检查,null指针 2. 排除最容易的情 …

要求:

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

实现思路:

  1. 安全检查,null指针

  2. 排除最容易的情况:长度、首/尾是否合法

  3. 遍历(第2~第len-1个元素):

    数字只考虑数值计算以及是否超出范围

    ” “前后只能为数字和”.”

    ”.”前后分别可以为数字或” “;”.”不能超过3个;更新数组索引

#include<stdio.h>  #include<string.h>    int is_digit(char ch)
{
  return (ch>='0' && ch<='9')? 1:0; } int ipv4_to_int(char* str, int* part) { int len=0,index=0,i=0; char* ps=str; if(ps == null || part ==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.%dn",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; }

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

 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/601178.html

(0)
上一篇 2021年5月9日
下一篇 2021年5月9日

精彩推荐