简体   繁体   中英

How to compare two ip address in c?

I am trying to compare ip address and see if it fits in a range (ie 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.

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.

As @deviantfan mentioned in the comments, I just need to have

htonl((rt_walker->dest).s_addr)

And it works perfect!!

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