c - inet_aton 转换 010.000.000.001 错误?

标签 c sockets inet-aton

我在使用 inet_aton 转换网络地址时遇到问题。下面的代码可以很好地转换地址 10.0.0.1

char *x1;
struct sockaddr_in si_other;
inet_aton("10.0.0.1", &si_other.sin_addr);
printf("si_other.sin_addr =%lu\n",si_other.sin_addr);
x1 = inet_ntoa(si_other.sin_addr);
printf("x1=%s\n",x1);

输出:

si_other.sin_addr =16777226
x1=10.0.0.01

目前没问题。但是,当传递 010.000.000.001

时,该函数工作异常
char *x2;
struct sockaddr_in si_other2;
inet_aton("010.000.000.001", &si_other2.sin_addr);
printf("si_other2.sin_addr =%lu\n",si_other2.sin_addr);
x2 = inet_ntoa(si_other2.sin_addr);
printf("x2=%s\n",x2);

输出:

si_other.sin_addr2 =16777224
x2=8.0.0.01

当传递 192.168.0.1192.168.000.001 时,该函数工作正常。

任何人都可以向我解释问题是什么以及如何解决问题吗? (注意:我需要在我的代码中将 IP 地址作为 010.000.000.001 传递)

最佳答案

前导 0 是 interpreted as indicating the number is octal . 010(十月)== 8(十二月)。您需要将输入修改为 inet_aton 以避免这种情况,或者您自己以不同的方式进行转换。

const char *str = "010.000.000.001";
inet_aton(str[0] == '0' ? str+1:str, &si_other.sin_addr);

这是最简单的解决方案,但最好首先修复生成字符串的任何内容 (snprintf?) 以避免混淆。

(就目前而言,该解决方案仍不适用于许多边缘情况,包括“001.0.0.1”、“0xF.0.0.1”、“1”和更多有效的 IPv4 地址)。

您可以使用 sscanf 简单地“规范化”您的输入,即使您一开始无法控制它是如何生成的(尽管这确实应该是一个错误,无论它来自于我的观点):

#include <stdio.h>
#include <stdlib.h>

int main() {
  const char *str="010.020.030.040";
  int parts[4];
  sscanf(str, "%d.%d.%d.%d", parts+0, parts+1, parts+2, parts+3);
  char *out = NULL;
  asprintf(&out, "%d.%d.%d.%d", parts[0], parts[1], parts[2], parts[3]);
  printf("%s\n", out);
  free(out);
  return 0;
}

关于c - inet_aton 转换 010.000.000.001 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14187515/

相关文章:

c malloc 问题(内存损坏)

c - 如何将 'convert' 两个(for 循环)转为一个(while 循环)?

mysql - 在 mysql 表中查找可用的 IP 范围

c# - 我的发送功能(套接字库:system.net&system.net.sockets)有一些错误

javascript - 有没有办法更改 Node.js 网络(套接字)库中的 "on"监听器?

c - IPv4 地址的 inet_aton 规范化

c - 如何根据从二进制文件读取的数据动态分配结构字段?

c++ - 跨平台,具有异步能力的 C/C++ HTTP 库

c - 如何检查套接字的另一端是否已被接受?