Reputation: 1021
I am trying to compare ip address and see if it fits in a range (i.e. network id and broadcast id)
starting =(rt_walker->dest).s_addr;
subnet = (rt_walker->mask).s_addr;
broadcast = starting | (~subnet);
if(ip_address>=starting && ip_address<=broadcast){
found_route =1;
}
This code works fine, but if i had "10.0.0.0" for rt_walker->dest then this line (rt_walker->dest).s_addr is giving me 10 instead of a 32bit binary value. So, if was comparing "10.0.0.0"(starting address) with "9.90.100.78"(IP_address that is getting compared) it always falls in range(10 - 10.255.255.255) which should not be true.
Upvotes: 1
Views: 4786
Reputation: 1021
As @deviantfan mentioned in the comments, I just need to have
htonl((rt_walker->dest).s_addr)
And it works perfect!!
Upvotes: 2
Reputation: 56
Here's a quick and easy way to compare two IP addresses:
int ipa_match(uint32_t addr1, uint32_t addr2, uint32_t mask)
{
return !((addr1 ^ addr2) & mask);
}
The XOR tells you which bits in the two addresses are different. The AND tells you if they differ in the masked portion. And the rest should be self-explanatory.
Upvotes: 3