搜索并替换字符串并忽略null字节字符
我正在开发一个 C 程序,它使用 NFQUEUE 来过滤另一个应用程序的流量。我需要做的事情之一是用另一个字符串替换数据包中包含的字符串。
问题是,数据包似乎随机包含空终止符字节(在字符串中间)。这意味着我看到的大多数使用 strstr() 的解决方案都不起作用。我需要找到类似的东西,它不会在到达空终止符字节时停止,而是允许指定长度并使用它。 (nfq_get_payload() 返回一个长度。)
我考虑过在执行替换之前用另一个字节替换空字节,然后在数据包发送之前恢复空字节。这种方法的问题是数据包有可能包含该字符,因此这不是最好的方法。我想我还可以找到一个不包含在数据包中的随机字节,但我宁愿避免这样做。
编辑:原始字符串和替换字符串的长度相同,均为 13 个字符。
I'm working on a C program that uses NFQUEUE to filter traffic for another application. One of the things I need to do is replace a string contained within a packet, with another string.
The problem is, the packets seem to contain the null terminator byte randomly (in the middle of the string). This means that most solutions I see, using strstr(), don't work. I need to find something similar that doesn't stop upon reaching a null terminator byte, but rather allows for a length to be specified and uses that instead. (nfq_get_payload() returns a length.)
I've looked at replacing the null bytes with another byte before performing the replace, and then restoring the null bytes before the packet is sent off. The problem with that approach is there's a chance the packet could contain the character, so that wouldn't be the best approach. I suppose I could also find a random byte that is not contained within the packet, but I'd rather avoid doing all that.
edit: Both the original string and replacement string are the same length, which is 13 characters.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能会对
memchr
如果找到一个字符可以为您工作。否则,您必须自己实现一个
memmem
实现或在网上找到一个实现。请注意,字符串搜索算法(因为
memmem
就是这样)可以具有广泛的性能特征,因此您希望找到一个基于高性能算法的算法(例如 这个看起来可以接受,但是你的里程数可能会有所不同)。You might be satisfied with
memchr
if finding one character can work for you. Otherwise, you would have to make amemmem
implementation yourself or find one online.Be aware that string-searching algorithms (because that's what
memmem
is) can have a wide range of performance characteristics, so you want to find one based on a performant algorithm (e.g. this one looks acceptable, but your mileage may vary).