如何在C语言中将char[]中的IP地址转换为Uint32_t?

9

我写了一个程序,它以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 Address %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个回答

15
您可以使用 inet_pton函数。对于另一种情况,您应该使用inet_ntop
针对Windows特定文档,请参见inet_ptoninet_ntop
请注意,这些函数可用于IPv4和IPv6。

4

如果您没有访问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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接