-1

我是 C 的新手,我正在尝试将这四个整数组合成一个整数。

srand(time(NULL));
int intOne = 1+rand()%255;
int intTwo = 1+rand()%255;
int intThree = 1+rand()%255;
int intFour = 1+rand()%255;

int allCombined = ("%i.%i.%i.%i", intOne, intTwo, intThree, intFour);
printf("%i", allCombined);

我需要做的就是将这四个整数组合成一个 IP 地址格式的变量。

示例:108.41.239.216

我将如何组合它们并将它们保存到变量中以供以后使用?

4

3 回答 3

1

有很多方法可以做到这一点,没有一种方法是正确的。我想到的自然解决方案(在您的代码片段的上下文中)是将它们存储在长度为 4 的整数数组中。然后您可以分别格式化它们。例如:

int ip_address[ 4 ] = { intOne, intTwo, intThree, intFour };

...然后当您想使用它时,如下所示:

printf( "%d.%d.%d.%d", ip_address[ 0 ], ip_address[ 1 ], ip_address[ 2 ], ip_address[ 3 ] );

...如果您需要访问部分 IP 地址,这也会给您带来优势,您可以在 O(1) 中执行此操作。

于 2013-08-15T19:03:21.220 回答
0

以下是您可以组合它们的几种方法:

  1. 将所有四个字节保存在一个无符号的 32 位整数中。第一个字节进入位 0 到 7,第二个字节进入位 8 到 15,依此类推。
  2. 创建一个struct包含四个值的。然后您可以将它们称为ipAddress.firstOctet,ipAddress.secondOctet等。
  3. 创建一个由四个字节组成的数组: ipAddress[0]ipAddress[1]等。
于 2013-08-15T19:07:39.677 回答
0

尝试这个:

#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main()
{
  srand(time(NULL ));
  int intOne = 1 + rand() % 255;
  int intTwo = 1 + rand() % 255;
  int intThree = 1 + rand() % 255;
  int intFour = 1 + rand() % 255;

  {
    struct in_addr ia = { 
      (intOne << 0) + (intTwo << 8) + (intThree << 16) + (intFour << 24) /* Here you initialise the integer. */
    };

    printf("0x%x", ntohl(ai.s_addr)); /* Convert the integer to the correct byte order (endianness) and print it. */
    printf("%s\n", inet_ntoa(ia)); /* Here you get the dotted version. */
  }

  return 0;
}
于 2013-08-15T19:19:37.300 回答