Search code examples
c++network-programmingip-addressforwarding

Matching destination address to forwarding table entry in C++


Essentially, I have two 4 byte IP addresses:

u_int32_t daddr; // in the packet
u_int32_t entry; // in the forwarding table

I also have a prefix that goes with entry in the forwarding table:

unsigned short prefix; // in forwarding table corresponding to entry

I need to match the daddr to the entry based on the prefix. I am pretty sure what this means is: if e.g the prefix is 23, then I have to match the first 23 bits of the entry with the daddr. I honestly don't even know where to start because I don't know how to match individual bits.

I have a forwarding table with lots of entries which each have a different prefix. I am not sure how to match the da with the correct entry.. Any help would be much appreciated. My daddr is stored in a standard ip header that I got from netinet ip.h file.

EDIT: I have find the "longest" match. So I am not comparing the entries to only check if they are equal, I am comparing them to determine how many bits are same. The best match is obviously when all of the bits are the same.


Solution

  • To compare only the top n bits of a and b of some unsigned type UInt:

    const unsigned int NBITS = sizeof(UInt) * CHAR_BIT;
    
    UInt a, b;
    
    if ((a >> (NBITS - n)) == (b >> (NBITS - n))) { /*...*/ }
    

    To compare the bottom m bits:

    if ((a << (NBITS - m)) == (b << (NBITS - m))) { /*...*/ }
    

    Some explanation: The type UInt has sizeof(UInt) bytes, and thus NBITS bits. To compare the top n bits, we simply shift both numbers to the right so that only n bits remain (the new top bits are filled in with zeros because the type is unsigned). To compare the bottom m bits, we shift both numbers to the left until all but m bits have fallen off the left (and zeros are filled in on the right):

    NBITS = 12, n = 4, m = 7:
    
         a:  1 2 3 4 x A B C D E F G
         b:  1 3 2 5 x A B C D E F G
    
    a >> 8:  0 0 0 0 0 0 0 0 1 2 3 4
    b >> 8:  0 0 0 0 0 0 0 0 1 3 2 5
    
    a << 5:  A B C D E F G 0 0 0 0 0
    b << 5:  A B C D E F G 0 0 0 0 0