简体   繁体   中英

Checking if given IP is part of an IP range using inet_pton()

inet_pton with AF_INET should provide an in_addr , whose member s_addr will have the equivalent numerical representation as an uint32_t type. I'm trying to use this property to check whether a given IP belongs to a range, as follows:

#include <iostream>
#include <sstream>
#include <arpa/inet.h>
using namespace std;

template <class T> void convert_from_str (string s, T &r) {
    stringstream ss(s);
    ss >> r;
}

int main () {
    string cidr = "10.0.0.0/8", ip = "10.32.11.195", ci;
    in_addr in1, in2;
    uint32_t mask;
    size_t len;

    len = cidr.find_first_of('/');
    ci = cidr.substr(0, len);
    convert_from_str(cidr.substr(len + 1, cidr.length()), mask);

    mask = 32 - mask;

    inet_pton(AF_INET, ip.c_str(), &in1);
    inet_pton(AF_INET, ci.c_str(), &in2);

    if (in1.s_addr >> mask == in2.s_addr >> mask) {
        cout << "in range" << endl;
    }
    else {
        cout << "not in range" << endl;
    }

    return 0;
}

However, this does not work as expected, producing "not in range" every time.

Where does the problem arise and what can I do to make it work?

s_addr is in network byte order; you need to pass the values to ntoh() to get them into host byte order before shifting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM