我试图比较这两个字符指针中的值,但得到了奇怪的输出:
第一个是(libpcap IP地址):
const char* ip_source = inet_ntop(AF_INET, &ip->ip_src, buffer1, sizeof(buffer1)); //192.168.56.1第二个是:
char *host_ip = inet_ntoa(((struct sockaddr_in*)a->addr)->sin_addr); //192.168.56.1我尝试过使用if (*ip_source == *host_ip)、if (strcmp(ip_source, host_ip) == 0)和if (strncmp(ip_source, host_ip, strlen(host_ip))。
如何比较存储在这两个变量中的IP地址,以查看这两个IP地址是否相同?
代码如下:
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");
}这就是结果:
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在本例中,它返回-2
发布于 2015-04-11 21:58:33
第一个只会比较每个字符的第一个字符,而strcmp在我看来是正确的。如果一个是const,另一个不是,应该没有关系。
发布于 2015-04-12 00:00:52
事实证明,问题出在inet_ntoa而不是字符串测试上。
捕获的每个数据包都会覆盖变量host_ip。
当我获得IP地址时,我使用了以下命令:
inet_ntoa(((struct sockaddr_in*)a->addr)->sin_addr);但每次捕获数据包时都会动态覆盖,因此将其更改为静态:
const char* host_ip = inet_ntop(AF_INET, &(((struct sockaddr_in*)a->addr)->sin_addr), buffer1, sizeof(buffer1));方法起作用了。
发布于 2015-04-12 01:07:54
为什么不直接比较地址,因为它们都是按网络字节顺序排列的?
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");
}https://stackoverflow.com/questions/29578640
复制相似问题