简体   繁体   中英

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

I write a program which takes IP address as an argument and i wanted to store this IP address in the unit32_t. I can easily convert uint32_t to back to character array. How to convert IP address in Char Array to uint32_t.

For example

./IPtoCHAR 1079733050

uint32_t to IP Address => 64.91.107.58

But how to write a program that does the reverse task?

./CHARtoIP 64.91.107.58


for the first IPtoCHAR, it is

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));

But all these below does not work

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);

You use the inet_pton . function

And for the other way around you should have used inet_ntop .


For Windows-specific documentation, see inet_pton and inet_ntop .


Note that the functions can be used for both IPv4 and IPv6.

In case you don't have access to inet_* functions or need to code this yourself due to any other strange reason, you can use a function like this:

#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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM