如何比较IPv6大于/小于C [英] How to compare an IPv6 is greater/less than in C
本文介绍了如何比较IPv6大于/小于C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 inet_pton
转换IPv4以比较它是否在IPv4范围内非常简单。但是,我不确定如何使用 inet_pton
和 in6_addr
来查看它是否小于另一个IP。这就是我的想法:
Converting an IPv4 with inet_pton
to compare if it's within a range of IPv4 is fairly simple. However, I'm not sure how to use inet_pton
and in6_addr
and see if it's less/greater than another IP. Here's what I was thinking:
#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
,因为它们以网络字节顺序存储(aka大字节序)。
You can use memcmp
for this since they're stored in network byte order (aka big endian).
if (memcmp(&result, &resfirst, sizeof(result)) > 0 && memcmp(&result, &reslast, sizeof(result)) < 0)
我想您可能是说> =
的意思,而且可能是< =
。
I think you might've meant >=
though and possibly <=
as well.
实际上,对于IPv4,您也必须这样做,至少在很少的情况下字节序机器。
In fact, you'd have to do it this way for IPv4 as well, at least on little endian machines.
这篇关于如何比较IPv6大于/小于C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文