Reputation:
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?
Upvotes: 0
Views: 576
Reputation: 18964
s_addr
is in network byte order; you need to pass the values to ntoh()
to get them into host byte order before shifting.
Upvotes: 3