Help with Network Address Math

Top Page
Attachments:
Message as email
+ (text/plain)
Delete this message
Reply to this message
Author: Kurt Granroth
Date:  
Subject: Help with Network Address Math
On Thursday 07 August 2003 01:10 pm, AZ Pete wrote:
> Calling all network gurus :)
>
> My IP network address math is rather rusty (it's been a long time!!). I
> have need to calculate whether a given client IP address is within a given
> network. Additionally, if there are a list of given networks, which one is
> the most specific. I need the math formulas to calculate these figures for
> use within an application.
>
> Examples:
> Given the network: 192.168.1.0/24
> Given IP address is: 192.168.1.100
>
> What is the formula to determine if this client's IP address falls within
> the network's range.
>
> Further example
> Given these networks: 192.168.1.0/24 and 192.168.0.0/16
> and the client IP of: 192.168.1.100
>
> In this case the client's IP falls within both networks. What is the
> formula to determine which network is the more specific one?


The IP address has four octets and the network mask (the /24, and /16) say
which octets determine the network. /8 masks say that only the first octet
matters (192.x.x.x), /16 denote the first two (192.168.x.x), and /24 denotes
the first three (192.168.1.x). There is also /32.. but we don't care about
that.

Figuring out if an IP address is in a given network is as simple as applying
the network mask to both the network and the IP and see if they match. If
you know that you will always deal with netmasks of 8, 16, or 24, then your
code can simply compare the first, second, and or third octets to see if they
match.

If you want to be more general, then you'll have to do some math.

First, convert the IP address to a hex number. Convert each octet separately.
192.168.1.100 -> C0A80164 (192->C0, 168->A8, 1->01, 100->64)

Do the same for the network
192.168.1.0 -> C0A80100

Convert the netmask to a hex number. This is done by shifting a full mask
(0xFFFFFFFF) by 32 minus the mask.
(FFFFFFFF << (32 - 8)) = FF000000
(FFFFFFFF << (32 - 16)) = FFFF0000
(FFFFFFFF << (32 - 24)) = FFFFFF00
(FFFFFFFF << (32 - 17)) = FFFF8000

AND the IP address with the mask
C0A80164 & FFFF0000 = C0A80000

AND the network with the mask
C0A80000 & FFFF0000 = C0A80000

Compare the two
C0A80000 = C0A8000

So is 192.168.128.25 in 192.168.192.0/18? Yes

1. 192.168.128.25 -> C0A88019
2. 192.168.192.0 -> C0A8C000
3. 18 -> FFFFC000
4. C0A88019 & FFFFC000 -> C0A88000
5. C0A8C000 & FFFFC000 -> C0A8C000
6. C0A8C000 = C0A8C000