LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Check if IP belongs to subnet (https://www.linuxquestions.org/questions/programming-9/check-if-ip-belongs-to-subnet-560888/)

krizzz 06-11-2007 09:42 AM

Check if IP belongs to subnet
 
Hi,

I'm looking to some quick and easy way to determine if the given IP address belongs to the subnet given as network and mask in the slash notation. Is it possible to do with some bitmask matching using some of already defined C structures?

Best,
Chris

krizzz 06-11-2007 10:39 AM

Ok, I think I have hound the answer but please correct me if I'm wrong. Is it as easy as ANDing the IP with the mask, then ANDing the network with the mask and comparing the results? I'm quite positive my thinking is OK but I'd need second opinion to be 100% assured.

jlinkels 06-11-2007 06:35 PM

Bottom line it comes to that. You AND both values (IP and network) and if the two values are equal you have a match.

IP was designed in an era that elegant solutions were appreciated instead of throwing in more CPU power to solve the problem of a crappy algorithm.

However beware that common notation for IP is 168.192.10.145 which is decimal and cannot be AND-ed.

Also, AFAIK "slash" notation is 168.192.10.0/24 meaning that the mask is 0xFFFFFF00 so you'd have to create that value from the /24 string.

jlinkels


All times are GMT -5. The time now is 06:57 AM.