Comparing strings containing IPv4 addresses in C

c, ipv4

Solution

You can try the sexy way, store all values in one unsigned integer and compare it.

  const char* ip1 = "192.168.145.123";
  const char* ip2 = "172.167.234.120";

  unsigned char s1, s2, s3, s4;
  unsigned int uip1, uip2;

  sscanf(ip1,"%hhu.%hhu.%hhu.%hhu",&s1,&s2,&s3,&s4);
  uip1 = (s1<<24) | (s2<<16) | (s3<<8) | s4; //store all values in 32bits unsigned int

  sscanf(ip2,"%hhu.%hhu.%hhu.%hhu",&s1,&s2,&s3,&s4);
  uip2 = (s1<<24) | (s2<<16) | (s3<<8) | s4;

  if (uip1 > uip2)
  {
    printf("ip1 greater !");   
  }
  else
  {
    printf("ip2 greater or equal !");     
  }

Problem

I have two strings `ip1 = "192.168.145.123"` and `ip2 = "172.167.234.120"`. I can compare these two strings for equality: ``` strncmp(ip1,ip2) == 0 ``` However how can I find out ``` if (ip1 > ip2) { ... } ``` What I have tried I can use sscanf: ``` sscanf(ip1,"%d.%d.%d.%d",&s1,&s2,&s3,&s4) ``` and store the numbers and compare. However in 32 bit I can't store the numbers as integers due to the upper limit. Thus I have no choice but to compare the integers as strings.

Original source

Related problems