c - 如何比较 IPv6 大于/小于 C

标签 c comparison ipv6

使用 inet_pton 转换 IPv4 以比较它是否在 IPv4 范围内是相当简单的。但是,我不确定如何使用 inet_ptonin6_addr 并查看它是否小于/大于另一个 IP。这是我的想法:

#include <arpa/inet.h>

  ...

const char *ip6str = "0:0:0:0:0:ffff:c0a8:3";
const char *first = "0:0:0:0:0:ffff:c0a8:1";
const char *last = "0:0:0:0:0:ffff:c0a8:5";

struct in6_addr result, resfirst, restlast;
uint8_t ipv6[16]; // perhaps to hold the result?

inet_pton(AF_INET6, first, &resfirst);
inet_pton(AF_INET6, last, &reslast);
inet_pton(AF_INET6, ip6str, &result);

//assuming inet_pton succeed
if(result.s6_addr >= resfirst.s6_addr && result.s6_addr <= reslast.s6_addr)
    //within range

最佳答案

您可以使用 memcmp为此,因为它们以网络字节顺序(又名大端)存储。

if (memcmp(&result, &resfirst, sizeof(result)) > 0 && memcmp(&result, &reslast, sizeof(result)) < 0)

我想你的意思可能是 >=虽然可能<=

事实上,对于 IPv4,您也必须这样做,至少在小端机器上是这样。

关于c - 如何比较 IPv6 大于/小于 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24723439/

相关文章:

c - 来自 char * 的 atoi 在 C 中返回 0

c - 如何在 linux 中将 c 文件构建到共享对象(库)中

c# - 如何在 C# 中使用 p/invoke 将指针传递给数组?

c - 在 C/C++ 中初始化大小未知的数组

c# - 与 Properties.Resources.image 的图像比较

c# - 自动比较属性

c# - IndexOf 与自定义 StringComparer

http - 在Rust中发送HTTP请求时如何使用IF_INET6-IPV6

azure - azure功能支持ipv6吗?

ios - Swift IPv6 支持