• C语言实现字符串IP与整数型IP的相互转换


    1. #include <stdio.h>  
    2. #include <stdlib.h>  
    3. #include <string.h>  
    4. #include <malloc.h>  
    5.   
    6. int main(int argc,char *argv[])  
    7. {  
    8.   
    9.     const char *ip ="192.168.34.232";  
    10.     char *ipstr=NULL;  
    11.     char str_ip_index[4]={''};  
    12.     unsigned int ip_int,ip_add=0,ip_int_index[4],ip_temp_numbr=24;  
    13.     int j =0,a=3;     
    14.     for(unsigned int i =0;i<=strlen(ip);i++)//要用到''  
    15.     {  
    16.         if (ip[i]==''||ip[i]=='.')  
    17.         {             
    18.             ip_int =atoi(str_ip_index);   
    19.             if (ip_int<0||ip_int>255)  
    20.             {  
    21.                 printf("IP地址有误 ");  
    22.                 system("pause");  
    23.                 return 0;                 
    24.             }  
    25.   
    26.             ip_add+=(ip_int*((unsigned int)pow(256.0,a)));            
    27.             a--;  
    28.             memset(str_ip_index,0,sizeof(str_ip_index));  
    29. //          for (int x=0;x<4;x++)  
    30. //          {  
    31. //              str_ip_index[x]='';  
    32. //          }  
    33.             j=0;  
    34.             continue;  
    35.         }  
    36.   
    37.         str_ip_index[j]=ip[i];  
    38.         j++;  
    39.     }     
    40.     printf("%u ",ip_add);  
    41.       
    42.     //转换成x.x.x.x  
    43.     for(j=0;j<4;j++)  
    44.     {  
    45.         ip_int_index[j]=(ip_add>>ip_temp_numbr)&0xFF;  
    46.         ip_temp_numbr-=8;  
    47.     }  
    48.   
    49.     if ((ipstr=(char *)malloc(17*sizeof(char)))==NULL)  
    50.     {  
    51.         return 0;  
    52.     }  
    53.       
    54.     sprintf(ipstr,"%d.%d.%d.%d",ip_int_index[0],ip_int_index[1],ip_int_index[2],ip_int_index[3]);  
    55.     printf("%s ",ipstr);  
    56.     free(ipstr);  
    57.     ipstr=NULL;  
    58.     system("pause");  
    59.     return 0;  
    60. }  

    转换效果:

  • 相关阅读:
    汉字乱码、加密后结果字符串不一致
    msgpack和TParams互相转换
    unigui监听会话开始和结束
    System.JSON.Builders.pas
    保证最终一致性的模式
    使用 Delta Sharing 协议进行数据共享
    dremio 16 升级问题
    graylog 4.0 运行
    supabase 开源firebase 可选工具
    cube.js 最新playground 说明
  • 原文地址:https://www.cnblogs.com/dpf-learn/p/7727552.html
Copyright © 2020-2023  润新知