简体   繁体   English

如何在C中比较两个IP地址?

[英]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) 我正在尝试比较ip地址,看它是否适合一个范围(例如,网络ID和广播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. 这段代码可以正常工作,但是如果我的rt​​_walker-> dest具有“ 10.0.0.0”,则此行(rt_walker-> dest).s_addr给我10而不是32位二进制值。 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. 因此,如果将“ 10.0.0.0”(起始地址)与“ 9.90.100.78”(要比较的IP地址)进行比较,则该值始终落在范围(10-10.255.255.255)中,这不应该为真。

Here's a quick and easy way to compare two IP addresses: 这是比较两个IP地址的快速简便的方法:

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. XOR告诉您两个地址中的哪些位不同。 The AND tells you if they differ in the masked portion. AND会告诉您它们在被掩盖部分是否不同。 And the rest should be self-explanatory. 其余的应该是不言自明的。

As @deviantfan mentioned in the comments, I just need to have 正如@deviantfan在评论中提到的,我只需要

htonl((rt_walker->dest).s_addr)

And it works perfect!! 而且效果很好!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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