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

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

转换效果:

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