如何将char []中的IP地址转换为c中的Uint32_t?

时间:2013-03-27 07:28:14

标签: c

我编写了一个以IP地址为参数的程序,我希望将这个IP地址存储在unit32_t中。我可以轻松地将uint32_t转换回字符数组。如何将Char Array中的IP地址转换为uint32_t。

例如

  

./ IPtoCHAR 1079733050

uint32_t到IP地址=> 64.91.107.58

但是如何编写一个执行相反任务的程序?

  

./ CHARtoIP 64.91.107.58


对于第一个IPtoCHAR,它是

  

unsigned int ipAddress = atoi(argv [1]);

     

printf(" IP地址%d。%d。%d。%d \ n",((ipAddress>>> 24)& 0xFF),((ipAddress>> 16 )& 0xFF),((ipAddress>>> 8)& 0xFF),(ipAddress& 0xFF));

但以下所有这些都不起作用

  

uint32_t aa =(uint32_t)(" 64.91.107.58");

     

uint32_t aa = atoi(" 64.91.107.58");

     

uint32_t aa = strtol(" 64.91.107.58",NULL,10);

2 个答案:

答案 0 :(得分:13)

您使用inet_pton。功能

另一方面,你应该使用inet_ntop


有关特定于Windows的文档,请参阅inet_ptoninet_ntop


请注意,这些功能可用于IPv4和IPv6。

答案 1 :(得分:3)

如果您无法访问inet_ *函数或由于任何其他奇怪的原因需要自己编写代码,您可以使用以下函数:

#include <stdio.h>

/**
 * Convert human readable IPv4 address to UINT32
 * @param pDottedQuad   Input C string e.g. "192.168.0.1"
 * @param pIpAddr       Output IP address as UINT32
 * return 1 on success, else 0
 */
int ipStringToNumber (const char*       pDottedQuad,
                              unsigned int *    pIpAddr)
{
   unsigned int            byte3;
   unsigned int            byte2;
   unsigned int            byte1;
   unsigned int            byte0;
   char              dummyString[2];

   /* The dummy string with specifier %1s searches for a non-whitespace char
    * after the last number. If it is found, the result of sscanf will be 5
    * instead of 4, indicating an erroneous format of the ip-address.
    */
   if (sscanf (pDottedQuad, "%u.%u.%u.%u%1s",
                  &byte3, &byte2, &byte1, &byte0, dummyString) == 4)
   {
      if (    (byte3 < 256)
           && (byte2 < 256)
           && (byte1 < 256)
           && (byte0 < 256)
         )
      {
         *pIpAddr  =   (byte3 << 24)
                     + (byte2 << 16)
                     + (byte1 << 8)
                     +  byte0;

         return 1;
      }
   }

   return 0;
}