c++ - inet_aton() 对无效 IP 地址返回成功?

标签 c++ c linux gcc ip

我正在寻找一些函数来验证给定的字符串是否是有效的 ipv4 地址, 但 inet_aton() 似乎对“11”和“1.1”等字符串感到满意
验证 ipv4 字符串的最佳方法是什么?

#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char *argv[])
{
    struct in_addr addr;

   if (argc != 2) {
        fprintf(stderr, "%s <dotted-address>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

   if (inet_aton(argv[1], &addr) == 0) {
        fprintf(stderr, "Invalid address\n");
        exit(EXIT_FAILURE);
    }

   printf("%s\n", inet_ntoa(addr));
    exit(EXIT_SUCCESS);
}

一些无效字符串的输出是

[root@ ~]# ./a.out 1.1
1.0.0.1
[root@ ~]# ./a.out "1 some junk"
0.0.0.1
[root@ ~]# ./a.out "10 some junk"
0.0.0.10

我想要一个例程来拒绝任何不是点分十进制表示法的字符串 x.x.x.x,x 从 0 到 255

最佳答案

这是 inet_aton 指定/记录的行为。

如果您只想接受点分四进制十进制表示法,请使用:

unsigned char *a = (void *)&addr, dummy;
if (sscanf(src, "%3hhd.%3hhd.%3hhd.%3hhd%c", a, a+1, a+2, a+3, &dummy)!=4) {
    /* error */
}

或者,您也可以使用 inet_pton 函数,该函数接受的格式更具限制性。

关于c++ - inet_aton() 对无效 IP 地址返回成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16327077/

相关文章:

c++ - 程序在短暂渲染后立即自动停止

c++ - 互斥保护 std::condition_variable

c++ - 如何确定 Windows 10 中是否打开了高对比度主题?

c - 如何在 linux 中使用 windows sockets 编译程序?

linux - 无法让 setenv 在 .htaccess 中工作

c++ - 使用自定义小部件自定义 QT QTreeView

c - malloc分配的内存在物理上不一定是连续的吗?

c - 如何在格式错误的输入中正确使用带循环的 sscanf?

close() 系统调用需要很长时间才能完成

linux - Linux 服务触发 Windows 警报?