0

I'm trying to compare the values in these two char pointers but i'm getting strange outputs:

The first one is (libpcap IP address):

const char* ip_source = inet_ntop(AF_INET, &ip->ip_src, buffer1, sizeof(buffer1)); //192.168.56.1

The second one is:

char *host_ip = inet_ntoa(((struct sockaddr_in*)a->addr)->sin_addr); //192.168.56.1

I've tried using if (*ip_source == *host_ip), if (strcmp(ip_source, host_ip) == 0) and if (strncmp(ip_source, host_ip, strlen(host_ip)).

How do I compare the IP addresses stored in these two variables to see if both IP addresses are the same?

This is the code:

if (strncmp(ip_source, host_ip, strlen(host_ip)) == 0) // if sent local > remote
{
    printf("   RST/ACK Detected [Local > Remote]\n");
}
else // if sent remote > local
{
    printf("   RST/ACK Detected [Remote > Local]\n");
}

This is the result:

Packet number 2386:
current time: 2015-04-11 15:07:59.412 
  From(src): 192.168.56.1 <---- Local (IP stored in *host_ip)
    To(dst): 192.168.56.2 <---- Remote
   Protocol: TCP
   Src port: 1864
   Dst port: 49750
    Seq Num: 0
    Ack Num: 3556812524
   RST/ACK Detected [Remote > Local] <--- Wrong

In this case it's returning -2

Crizly
  • 971
  • 1
  • 12
  • 33

3 Answers3

0

Ths first would just compare the first character of each, while strcmp looks right to me. Should not matter if one is const and the other not.

Bjorn Munch
  • 496
  • 2
  • 6
  • I've tried using strncmp(ip_source, host_ip, strlen(host_ip) to compare all characters but it's still not working – Crizly Apr 11 '15 at 14:20
0

As it turns out the issue was with inet_ntoa rather than the string test.

The variable host_ip was being overwritten with every packet captured.

When I got the IP address I used this:

inet_ntoa(((struct sockaddr_in*)a->addr)->sin_addr);

But that dynamically overwrites every time a packet is captured, so changing it to the static:

const char* host_ip = inet_ntop(AF_INET, &(((struct sockaddr_in*)a->addr)->sin_addr), buffer1, sizeof(buffer1));

Method worked.

Crizly
  • 971
  • 1
  • 12
  • 33
  • That's an issue with `inet_ntoa()`, not libpcap. The man page on OS X says "The string returned by inet_ntoa() resides in a static memory area.", which is true on other OSes as well, and that means that if *any* other code calls `inet_ntoa()`, it overwrites the previous value. –  Apr 11 '15 at 17:03
0

Why not just compare the addresses directly, as they're both in network byte order?

if (memcmp(&ip->ip_src, &((struct sockaddr_in*)a->addr)->sin_addr.s_addr, 4) == 0) {
    printf("   RST/ACK Detected [Local > Remote]\n");
} else {
    printf("   RST/ACK Detected [Remote > Local]\n");
}