8

IPアドレスを引数として取るプログラムを作成し、このIPアドレスをunit32_tに格納したいと思いました。uint32_tを文字配列に簡単に戻すことができます。Char配列の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);

4

2 に答える 2

14

を使用しinet_ptonます。働き

逆に、を使用する必要がありますinet_ntop


Windows固有のドキュメントについては、およびを参照inet_ptonしてくださいinet_ntop


この機能は、IPv4とIPv6の両方で使用できることに注意してください。

于 2013-03-27T07:30:02.503 に答える
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;
}
于 2016-03-30T14:43:29.667 に答える