The Comparison Function (cont.)

Comparing two HTTP codes is a particularly simple task. Since an HTTP code is simply an integer, we can use the built in C comparison functions <, >, <=, >=, ==, !=, for comparing whether one integer is less than, greater than, less than or equal to, greater than or equal to, equal to or not equal to a second integer, respectively.

In fact in our case there is an even simpler way of doing things. Since our comparison function is merely supposed to return a value less than zero, equal to zero or greater than zero depending whether the the first HTTP code is less than, equal to or greater than the second, respectively, then we can simply return the difference between the two codes, which will automatically be a value of the required kind.

Comparing IP addresses is slightly more complicated. Here there are four numbers for each IP address. In many locations the first two or even three of these numbers remains the same, whilst the fourth number in the IP address is used to differentiate machines all on the same network, or in virtually the same location. Therefore if the first digit of two IP addresses differ, then there is not much point comparing the latter digits, and so on, since the machines are almost certainly in entirely different places, if not countries.

We can again use the same trick of subtracting the first digit of one IP address from that of the second IP address in order to perform our comparison. However if the difference is zero (i.e. the first digit for both addresses is the same) then we need to proceed to the second digits to see how they differ, and so on, right down to the fourth digits.

Our comparison function may now be implemented as follows-na:

int compare(logType * line1, logType * line2, int flag)
{
    if (flag == HTTP_FLAG) return (line1->http - line2->http);
    if (line1->ip.int1 != line2->ip.int1) 
        return (line1->ip.int1 - line2->ip.int1);
    if (line1->ip.int2 != line2->ip.int2) 
        return (line1->ip.int2 - line2->ip.int2);
    if (line1->ip.int3 != line2->ip.int3)
        return (line1->ip.int3 - line2->ip.int3);
    return (line1->ip.int4 - line2->ip.int4);
}

This function assumes that if the flag is not HTTP_FLAG then it is the other kind. It performs no check that a valid flag has been used. At each point in the function things only continue on if the last condition checked was not true, else the function returns with the correct value. Finally if the function gets to the last line, then the flag is not HTTP_FLAG, so we are presumably comparing IP addresses, and the other three tests have failed, meaning that the first three numbers in the two IP addresses being compared are the same. One then simply returns the result of subtracting the fourth numbers of the two IP addresses.