Compare IP addresses

Friends,

I want to compare two IP addresses, so that I may compare which is more/less "specific" or "restricted" than the other.

So is there any function/library that may help in doing this comparison in C?

Bye.
 
Don't know how IP #1 may be more specific than IP#2...

Are you talking about comparing subnets? If yes, you can compare CIDR for them since /32 is more specific than /24.
 
Hi,
I'm not sure if you wan't to compare two IP addresses. If yes, they are just numbers; you can compare them as such.

Somehow I've got a feeling you want to compare routes to a specific destination or subnets.
Can you give us more details what are you trying to achieve?

As Alt suggested you can compare MASKs (or CIDRs depending what you are working with).

It can get interesting if you are trying to program auto-summary of a routing protocols and you are trying to find a supernet.
 
Code:
int inaddr_cmp( const char * a, const char * b, const char * netmask, size_t nmemb )
{
  size_t i;
  for( i=0; i!=nmemb; ++i )
  {
    if( a[i] & netmask[i] > b[i] & netmask[i] )
      return 1;
    if( a[i] & netmask[i] < b[i] & netmask[i] )
      return -1;
  }
  return 0;
}
?

if it's just normal host addresses (as opposed to net addresses) just use C's `!=` or `==` operators on uint32_t for ipv4 and uint128_t for ipv6 (if availible)
 
Back
Top