簡體   English   中英

如何將char []中的IP地址轉換為c中的Uint32_t?

[英]how to convert IP address in char[] to Uint32_t in c?

我寫了一個以IP地址為參數的程序,我想將此IP地址存儲在unit32_t中。 我可以輕松地將uint32_t轉換回字符數組。 如何將字符數組中的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);

您使用inet_pton 功能

對於其他方法,您應該使用inet_ntop


有關特定於Windows的文檔,請參見inet_ptoninet_ntop


請注意,這些功能可用於IPv4和IPv6。

如果您由於其他任何奇怪的原因而無法訪問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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM