复制缓冲区中的IP地址

时间:2018-05-10 14:29:42

标签: c pointers network-programming ip

我在C中构建防火墙,我遇到以下问题。我在客户端要求一个IP地址,我得到4个数字(IP地址的八位字节采用点分四格式)。 就像在这个例子中一样:

255.255.197.0

我在整数类型数据中获得了这4个八位字节。要将其复制到字符的缓冲区中,我使用 sprintf() 功能,但我收到了分段错误。

char buffer[MAX_BUFF_SIZE];            // The buffer to save the IP address
bzero(buffer, sizeof(buffer));    // Clean the buffer

// Gets the address
int o1, o2, o3, o4;
do
{ 
  printf("Introduce the 4 octets of the IP address (dotted quad format).\n");
  printf("Numbers must go from 0 to 255.\n\n");

  valid = TRUE;
  printf("Introduce first octet (X.-.-.-): ");
  scanf("%d", &o1);
  printf("Introduce second octet (-.X.-.-): ");
  scanf("%d", &o2);
  printf("Introduce third octet (-.-.X.-): ");
  scanf("%d", &o3);
  printf("Introduce fourth octet (-.-.-.X): ");
  scanf("%d", &o4);
  if (o1 < 0 || o1 > 255 || o2 < 0 || o2 > 255 || o3 < 0 || o3 > 255 || o4 < 0 || o4 > 255)
  {
    printf("Error [Client]: Invalid number.\n");
    valid = FALSE;
  }
} while (valid == FALSE);

// When octets are valid
sprintf(buffer, "%d.%d.%d.%d", o1, o2, o3, o4); // Copy the address in String format in buffer
inet_aton(buffer, &my_rule.addr);
printf("The IP address is %s\n", my_rule.addr);

o1o2o3o4是地址的4个八位字节。知道如何将这个整数放入char缓冲区吗?

0 个答案:

没有答案