我有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.1和192.168.000.001时,该函数正常工作.
任何人都可以解释我是什么问题以及如何解决问题? (注意:我需要在我的代码中将IP地址作为010.000.000.001传递)
解决方法
前导0为
interpreted as indicating the number is octal. 010(oct)== 8(dec).您需要修改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,parts[0],parts[1],parts[2],parts[3]);
printf("%s\n",out);
free(out);
return 0;
}