C中的字符串匹配

人气:261 发布:2022-09-22 标签: ubuntu c++ c

问题描述

您好。我正在编写一个简单的IDS,但我遇到了问题。在下面的代码中,这段代码已编译并运行,但它只运行1循环然后退出程序..如何为循环运行它? 我认为它是由strcpy()函数停止的..

Hello. I am writing a simple IDS and I had a problems.. In the code below this code is compiled and running but it just run 1 loop then exited the program.. How to run it all for the loop? I think it's stopped by strcpy() function..

void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet)
{
    const struct sniff_ethernet *ethernet;  /* The ethernet header [1] */
    const struct sniff_ip *ip;              /* The IP header */
    

    char *src, *dst;
 



        //Return the first one;
    strcpy(src , inet_ntoa(ip->ip_src));
    strcpy(dst , inet_ntoa(ip->ip_dst));




if(src=dst)
{
printf("LAND");
}
else if(src!=dst)
{
printf("normal");
}
}

我正在使用pcap库..

I am using pcap library..

推荐答案

你好, 比较指针而不是字符串。 首先你没有分配内存 src dst 可能导致崩溃的变量。 要比较字符串,请使用strcmp或memcmp函数。 Hello, You comparing the pointers but not the strings. First you are not allocating the memory for src and dst variables which may cause crash. To compare strings this way use strcmp or memcmp functions.
char src[100],dst[100];
strcpy(src , inet_ntoa(ip->ip_src));
strcpy(dst , inet_ntoa(ip->ip_dst));
if (strcmp(src,dst) == 0)
{
}
else
{
}

问候, Maxim。

Regards, Maxim.

关于你的问题:我的代码中没有看到任何循环。 但是,无论如何,你似乎已经混淆了几个简单的概念: Regarding your question: I don't see any loop in your code. But anyway, you seem to have confused a couple of simple concepts:
char *src, *dst;
strcpy(src , inet_ntoa(ip->ip_src));
strcpy(dst , inet_ntoa(ip->ip_dst));

src和dst只是未初始化的指针,它们可能指向任何地方。所以strcpy会随机覆盖程序中的一些内存。

src and dst are just uninitialized pointers and they might point anywhere. So the strcpy is going to overwrite randomly some memory in your program.

if(src=dst)
{
    printf("LAND");
}
else if(src!=dst)
{
    printf("normal");
}

在if语句中,您将=与==混淆。而else分支中的if(src!= dst)是无用的。如果src不等于dst,那显然必须是不相等的!

In the if-statement you confused "=" with "==". And the "if (src!=dst)" in the else branch is useless. if src is not equal dst it must obviously be non-equal!

嗨! 首先 Hi! First of all
if(src=dst)

错误。你的意思是:

is wrong. You probably mean:

if(src==dst)

然而,由于你在比较指针,它仍然不会带来预期的结果。 如果你想比较C中的字符串,你应该使用 strcmp 功能。 它在string.h中定义

However, that still would not bring the desired results, since you are comparing pointers. If you want to compare strings in C, you should use the strcmp function. It is defined in string.h

#include <string.h> //In C
#include <cstring> //In C++

所以,例如代码看起来像这样:

So, for example the code would look something like this:

#include <cstring>

...

if(strcmp(src, dst) == 0)
{
    printf("LAND");
}
else
{
    printf("normal");
}

希望我没有误解任何事情:)

Hope I didn't misunderstand anything :)

607