0

不知道我错过了什么。我正在尝试确定 IP 地址 172.27.12.32 是否在 IP 地址 20.0.0.0 和 255.255.252.0 的范围内

我正在做的是以下内容:

std::string one("200.0.0.0");
std::string two("172.27.12.32");
std::string three("255.255.255.255");

long one_addr = inet_addr(one.c_str());
long two_addr = inet_addr(two.c_str());
long three_addr = inet_addr(three.c_str());

one_addr 等于 200 two_addr 等于 537664428 three_addr 等于 4294967295

two_addr 大于 one_addr 但如果最小 IP 地址为 200.0.0.0,则 172.27.12.32 不在范围内

如何确定 172.27.12.32 是否不在 200.0.0.0 和 255.255.255.255 范围内?

4

2 回答 2

4

提示:=)(http://www.stev.org/post/2012/08/09/C++-Check-an-IP-Address-is-in-a-IPMask-range.aspx

uint32_t IPToUInt(const std::string ip) {
    int a, b, c, d;
    uint32_t addr = 0;

    if (sscanf(ip.c_str(), "%d.%d.%d.%d", &a, &b, &c, &d) != 4)
       return 0;

    addr = a << 24;
    addr |= b << 16;
    addr |= c << 8;
    addr |= d;
    return addr;
}

希望这足以回答你的问题

于 2013-04-22T21:58:29.093 回答
0

inet_addr()函数返回一个in_addr_t结构实例:

in_addr_t inet_addr(const char *cp);

这通常是 32 位整数的 typedef,在每个架构上并不总是很长。

无论如何,请考虑将20.0.0.0and转换255.255.252.0in_addr_t值。然后将这些结果与您感兴趣的值进行比较。你会期待什么?

于 2013-04-22T22:01:44.390 回答