tags:

views:

19

answers:

2

Hello,

I am working with a BGP table of the Internet (a huge file). However, route summarization can be a problem. My main issue is that, sometimes, big chunks of IPv4 space are announced (i.e., 172.16.0.0/16), but also more specific and smaller routes are announced too (i.e., 172.16.64.0/18). So there are two redundant entries in the BGP table.

I would like to figure out a way to end up with a list of non-redundant IP addresses, just the big chunks. I am thinking of maybe comparing all of them and storing them in a list. Is there a method in C# to know if an IP address is part of a broader IP address? As in:

172.16.64.0/18 is part of 172.16.0.0/16 //true

Thanks a lot for all your help!

alemangui

+1  A: 

Use simple math.

IP address is 4 bytes, iow a 32-bit integer. The subnet mask is exactly the same.

Given this, you can use an arithmetic AND to determine whether it is inside or outside the defined network.

EG:

IP: 192.168.0.1      = C0 . A8 . 00 . 01
Subnet: 192.168.0.0  = C0 . A8 . 00 . 00

Is in subnet?
Thus 0xC0A80001 & 0xC0A80000 == 0xC0A80000 => true

To answer the question of whether one net work exists in another, you can use the same approach, but right shift both numbers with the size of the 'largest' subnet.

EG:

Net A: 172.16.64.0/18 -> AC 10 40 00
Net B: 172.16.0.0/16  -> AC 10 00 00

Thus right shift both with 16 and apply previous op.

AC 10 & AC 10 == AC 10 -> true
leppie
A: 

Consider the bit patterns:

172.16.64.0

10101100.00010000.01000000.00000000

172.16.0.0

10101100.00010000.00000000.00000000

Note that the set bits in the more-specific address are the set bits in the more-general address, plus some more. So if we perform a bitwise AND on the two addresses, the result will be equal to the more-general.

Is this always a correct test? Well, if we have two addresses that do not have a containment relationship, ANDing the bits will clearly give a result which has at least one bit different from the proposed parent, so this is the test we want.

If you know which of your two addresses is the proposed parent, and which is the proposed child, then we can simply AND the bits and compare to the proposed parent. If they could be in either order, AND them and compare to both inputs separately.

To get at the actual bits, if you already have an IPAddress, use GetAddressBytes to get a byte[], use BitConverter to get a unit, then just use & for the bitwise AND.

AakashM